java檔案上傳Demo,檔案上傳demo
說到檔案上傳我們要做到:
1.引入兩個包:commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar
2.將form改為上傳檔案模式:enctype="multipart/form-data"
3.開始編寫相關代碼
這裡會用到幾個關鍵的類:磁碟檔案工廠DiskFileItemFactory ; 建立servlet檔案上傳類:ServletFileUpload
還有幾個重要的方法:DiskFileItemFactory類用於將以臨時檔案形式儲存在磁碟上的存放目錄的方法setRepository;
ServletFileUpload類得到表單中所有的資料,得到form表單中所有的元素方法:parseRequest
下面看具體代碼:
說明以這種方式上傳檔案是儲存在伺服器端的!
import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.ArrayList;import java.util.List;import java.util.UUID;import javax.servlet.ServletException;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.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.io.FileUtils;public class UploadServlet extends HttpServlet {/** * Constructor of the object. */public UploadServlet() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();DiskFileItemFactory sf= new DiskFileItemFactory();//執行個體化磁碟被檔案清單工廠String path = request.getRealPath("/upload");//得到上傳檔案的存放目錄sf.setRepository(new File(path));//設定檔案存放目錄sf.setSizeThreshold(1024*1024);//設定檔案上傳小於1M放在記憶體中String rename = "";//檔案新產生的檔案名稱String fileName = "";//檔案原名稱String name = "";//普通field欄位//從工廠得到servletupload檔案上傳類ServletFileUpload sfu = new ServletFileUpload(sf);try {List<FileItem> lst = sfu.parseRequest(request);//得到request中所有的元素for (FileItem fileItem : lst) {if(fileItem.isFormField()){if("name".equals(fileItem.getFieldName())){name = fileItem.getString("UTF-8");}}else{//獲得檔案名稱fileName = fileItem.getName();fileName = fileName.substring(fileName.lastIndexOf("\\")+1);String houzhui = fileName.substring(fileName.lastIndexOf("."));rename = UUID.randomUUID()+houzhui;fileItem.write(new File(path, rename));}}} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("普通欄位"+name);System.out.println("檔案名稱"+fileName);System.out.println("修改後產生的檔案名稱"+rename);response.sendRedirect("ok.jsp");out.flush();out.close();}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}
index.jsp頁面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>檔案測試介面</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"> </head> <body> <div align="center"> <form action="UploadServlet" enctype="multipart/form-data" method="post"> 名稱:<input name="name" /> <br> 圖片:<input name="img" type="file"/><br> <input type="submit" value="提交" /> <input type="reset" value="重設" /> </form> </div> </body></html>
ok.jsp頁面:
<body> <h1 align="center">上傳檔案成功!</h1> </body>
實現效果就不了,有需要自己那過去用!