檔案上傳Servlet例項
阿新 • • 發佈:2019-02-16
package com.hbsi.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Arrays; 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 javax.servlet.jsp.PageContext; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.FileUploadBase.FileUploadIOException; import org.apache.commons.fileupload.disk.DiskFileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadServlet3 extends HttpServlet { /** * Constructor of the object. */ public UploadServlet3() { 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 { 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 */ private List fileType=Arrays.asList(".jsp",".jar",".txt"); public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //檔案上傳 try { //(1)建立一個解析器工廠---FileItem物件 DiskFileItemFactory factory=new DiskFileItemFactory(); factory.setRepository(new File(this.getServletContext().getRealPath("/temp")));//將臨時檔案存在指定路徑 //(2)得到解析器 ServletFileUpload upload=new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8"); upload.setFileSizeMax(1024*1024); upload.setProgressListener(new ProgerssHandle());//檔案上傳進度監聽器 //(3)對請求進行解析,有幾個輸入項,就會解析幾個FileItem物件 List<FileItem> list=upload.parseRequest(request); //(4)迭代list集合,對裡邊的每一個輸入想進行處理(獲取每一個輸入項) for(FileItem item:list){ //(5)判斷輸入的型別 if(item.isFormField()){ //普通輸入項 String inputName=item.getFieldName(); String inputValue=item.getString(); inputValue=new String(inputValue.getBytes("iso8859-1"),"utf-8"); System.out.println(inputName+" "+inputValue); //普通的輸入有亂碼如何解決 }else{ //上傳檔案的輸入項 String filename=item.getName();//上傳檔案的檔名字 if(!filename.trim().equals("")){//擷取掉名字兩邊的空串,和空串比較看是否為空串決定是否執行程式 filename=filename.substring(filename.lastIndexOf("\\")+1);//獲取檔名(不包括路徑) String ext=filename.substring(filename.lastIndexOf("."));//獲取副檔名 if(!fileType.contains(ext)){ request.setAttribute("message","上傳失敗--檔案型別只能是jpg,txt,jar"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } //得到輸出留物件 InputStream is=item.getInputStream(); //首先確定上傳檔案要儲存在那個目錄下 String savePath=this.getServletContext().getRealPath("WEB-INF/Upload"); //upload下建多級的子目錄 savePath=generateFilePath(savePath,filename); //對檔名進行了加工 filename=UUID.randomUUID().toString()+"_"+filename; //構建輸出流物件 FileOutputStream fos=new FileOutputStream(savePath+"\\"+filename); byte[] buff=new byte[1024]; int len=0; while((len=is.read(buff))>0){ fos.write(buff,0,len); } is.close(); fos.close(); item.delete();//刪除的是臨時檔案 } } } request.setAttribute("message", "上傳成功"); }catch(FileUploadBase.FileUploadIOException e){ request.setAttribute("message","上傳檔案太大不能超過1M"); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); request.setAttribute("message","上傳失敗"); } request.getRequestDispatcher("/message.jsp").forward(request, response); } public String generateFilePath(String path,String filename){ // 產生目錄結構的演算法:hash目錄 int dir1=filename.hashCode() & 0x0f;//一級目錄名 int dir2=filename.hashCode() >>4 & 0x0f; String savePath=dir1+"\\"+dir2+"\\"; File f=new File(savePath); if(!f.exists()){//判斷目錄是否存在 f.mkdirs();//多級目錄結構建立 } return savePath; } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } class ProgerssHandle implements ProgressListener{ public void update(long arg0, long arg1, int arg2) { // TODO Auto-generated method stub System.out.println("已經處理了"+arg0+"資料,總資料是"+arg1+"正在處理第"+arg2+"個數據"); } } }