1. 程式人生 > >實際應用二:基於Apache common fileupload的檔案上傳

實際應用二:基於Apache common fileupload的檔案上傳

第一步:編輯前臺頁面

主要以表單形式提交,後面會將ajax提交其實他也是封裝成表單資料
<form method="POST" enctype="multipart/form-data" action="fileupload">

             File to upload: <input type="file" name="upfile"><br/>

             Notes about the file: <input type="text" name="note"><br/> <br/>

            <input type="submit" value="Press"> to upload the file!

</form>

注意表單一定要寫enctype="multipart/form-data",不然識別不到

 

第二步:編輯後臺servlet

package com.lb.excel;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.MultipartStream.MalformedStreamException;
import org.apache.commons.fileupload.RequestContext;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.fileupload.util.Streams;


@WebServlet("/fileupload")
public class excelimp extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(111);
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=utf-8;");
		
		PrintWriter out = response.getWriter();

		//檢查我們是否有檔案上傳請求
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		System.out.println(isMultipart);

		if(isMultipart) {

			HttpServletRequest servletRequest = request;
			RequestContext ctx = new ServletRequestContext(servletRequest);

			FileItemFactory fileItemFactory = new DiskFileItemFactory();

			ServletFileUpload upload = new ServletFileUpload();
			FileItemIterator iter = null;
			
			try {
				iter = upload.getItemIterator(ctx);
			} catch (FileUploadException e1) {
				e1.printStackTrace();
			}
			
			try {
			    while (iter.hasNext()) {
			        FileItemStream item = iter.next();
			        FileItem fileItem = fileItemFactory.createItem(item.getFieldName(),
			                                                       item.getContentType(),
			                                                       item.isFormField(),
			                                                       item.getName());
			        Streams.copy(item.openStream(), fileItem.getOutputStream(), true);
			        
			        System.out.println("開始儲存");
			        InputStream in = fileItem.getInputStream();
                    //...檔案儲存操作....
			        System.out.println("儲存完成");
			        
			    }
			} catch (MalformedStreamException e) {
				e.printStackTrace();
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			
		}else {
			out.println(-1);
		}

	}

}

詳情可參考:http://commons.apache.org/proper/commons-fileupload/index.html

                      http://commons.apache.org/proper/commons-fileupload/using.html

 

上述提交會存在頁面重新重新整理的問題,那我們看看如何用ajax提交;

var self = this;
var file = event.target.files[0];
var form = new FormData();
form.append("file", file);
console.info(file);

$.ajax({
     url: "/Excelimpl/excelimp",
     type: "post",
     data: form,
     cache: false,
     processData: false,
     contentType: false,
     dataType: "json",
     success: function (result) {
              console.info(result);
              result.splice(0, 1);
      }

})

只需將檔案封裝成變表單資料即可。