JavaWeb 파일 다운로드 기능 인스턴스 코드

업무 중에 만난 파일을 다운로드하는 기능은 스스로 추출합니다. 코드가 간단합니다. 여러분에게 도움이 되었으면 합니다. 자, 말이 많지 않습니다. 코드를 올리십시오!

public void downloadFile(File file, String downName, HttpServletRequest request, HttpServletResponse response) {
 OutputStream out = null;
 FileInputStream fin = null;
 BufferedInputStream bin = null;
 try {
  if (file.exists()) {
  String finalFileName = null;
  String agent = request.getHeader("User-Agent");
  boolean isMSIE = (agent != null && agent.indexOf("MSIE") != -1);
  if (isMSIE) {
   finalFileName = URLEncoder.encode(downName, "UTF8");
  } else {
   finalFileName = new String(downName.getBytes("UTF-8"), "ISO-8859-1");
  }
  response.setContentType("application/x-msdownload");
  response.setHeader("Content-Disposition", "attachment; filename=".concat(finalFileName));
  out = response.getOutputStream();
  fin = new FileInputStream(file);
  bin = new BufferedInputStream(fin);
  for (int data = bin.read(); data > -1; data = bin.read()) {
   out.write(data);
  }
  } else {
  }
 } catch (Exception e) {
  e.printStackTrace();
 } finally {
  try {
  if (bin != null)
   bin.close();
  if (fin != null)
   fin.close();
  if (out != null)
   out.close();
  } catch (Exception e2) {
  e2.printStackTrace();
  }
 }
 }
이상은 본고의 JavaWeb 파일을 다운로드한 코드입니다. 여러분의 학습에 도움이 되고 저희를 많이 사랑해 주시기 바랍니다.

좋은 웹페이지 즐겨찾기