java組件commons-fileupload實現檔案上傳、下載、線上開啟_java

來源:互聯網
上載者:User

最近做了一個檔案上傳、下載、與線上開啟檔案的功能,剛開始對檔案上傳的介面中含有其它表單(例如輸入框、密碼等)在上傳的過程中遇到了許多問題,下面我寫了一個同時實現檔案上傳、下載、線上開啟檔案的測試程式。

首先請看效果圖:

 

核心代碼:

package com.jefry;  import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.Iterator; import java.util.List;  import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;   import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload;  /**  * Servlet implementation class FileUpload  */ public class FileUpload extends HttpServlet {  private static final long serialVersionUID = 1L;  private static final String fileDir = "F:/";  /**  * Default constructor.  */  public FileUpload() {    }   protected void doGet(HttpServletRequest request,   HttpServletResponse response) throws ServletException, IOException {   String aFileName = request.getParameter("fileName");  String online = request.getParameter("online");  FileInputStream in = null;  ServletOutputStream out = null;  boolean isOnLine = online != null ? true : false ;  try {       if(isOnLine){   URL u = new URL("file:///"+fileDir + aFileName);   response.setContentType(u.openConnection().getContentType());   response.setHeader("Content-Disposition", "inline; filename="+aFileName);   }   else{   response.setContentType("application/x-msdownload");   response.setHeader("Content-Disposition", "attachment; filename=" + aFileName);   }     in = new FileInputStream(fileDir + aFileName);   out = response.getOutputStream();   out.flush();   int aRead = 0;   while ((aRead = in.read()) != -1 & in != null) {   out.write(aRead);   }   out.flush();    } catch (Throwable e) {   e.printStackTrace();  } finally {   try {   in.close();   out.close();   } catch (Throwable e) {   e.printStackTrace();   }  }   }   protected void doPost(HttpServletRequest request,   HttpServletResponse response) throws ServletException, IOException {  try {   DiskFileItemFactory fileFactory = new DiskFileItemFactory();   ServletFileUpload fu = new ServletFileUpload(fileFactory);   List fileItems = fu.parseRequest(request);   Iterator iter = fileItems.iterator();   String uploader = null;   String date = null;   List<String> fileNames = new ArrayList<String>();   while (iter.hasNext()) {   FileItem item = (FileItem) iter.next();   if (!item.isFormField()) { // 檔案    String oldFileName = item.getName();    String newFileName = null;    int delimiter = oldFileName.lastIndexOf("/");    if (delimiter == -1)    newFileName = oldFileName.substring(delimiter + 1);    else    newFileName = oldFileName;    fileNames.add(newFileName);    item.write(new File(fileDir + newFileName));   } else { // 表單    String fieldName = item.getFieldName();    if ("uploader".equals(fieldName)) {    uploader = item.getString();    } else if ("date".equals(fieldName)) {    date = item.getString();    }   }   }   request.setAttribute("fileNames",fileNames);   request.getRequestDispatcher("download.jsp").forward(request, response);  } catch (Exception e) {   }  }  } 

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body>  <form action="FileUpload" method="post" enctype="multipart/form-data">  <br>  檔案一:<input type="file" name="file1" /> <br>  檔案二:<input type="file" name="file2" /> <br>  上傳者:<input type="text" name="uploader"/> <br>   日期:<input type="text" name="date"/> <br>   <input type="submit" value="提交"/>   </form> </body> </html> 

download.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  <%@page import="java.util.List"%><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body>   <br>  --------------直接下載------------  <br>  <%  List<String> fileNames = (List<String> )request.getAttribute("fileNames");  for(String fileName : fileNames) {  %>   <form action="FileUpload" method="get">   <input type="hidden" name="fileName" value="<%=fileName %>" />   <input type="submit" value="下載:<%=fileName %>" />  </form>  <%  }  %>  <br>  --------------直接開啟---------  <%  for(String fileName : fileNames) {  %>  <form action="FileUpload" method="get">   <input type="hidden" name="fileName" value="<%=fileName %>" />   <input type="hidden" name="online" value="yes" />   <input type="submit" value="開啟:<%=fileName %>" />  </form>  <%  }  %>  </br>  </body> </html> 

本文已被整理到了《Java上傳操作技巧匯總》,歡迎大家學習閱讀。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.