Flex4: How to Upload File to Servlet (Part II)
1. In this part, we focus on server side programming:
1) At what format did the data sent from Flex?
2) How did Servlet get data sent from Flex?
3) How did Servlet send response to Flex to notify upload finished?
4) How to make it easier for common file upload?
2. Use commons-io-2.4.jar and commons-fileupload-1.3.jar for easier file upload
package edu.xmu.servlet; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; 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; public class FileUploadServlet extends HttpServlet { private int maxPostSize = 1024 * 1024 * 1024; private String uploadPath = "E:/SampleUploadFolder/"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("doGet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("doPost"); req.setCharacterEncoding("UTF-8"); // If we don't add this, garbled may occur with Chinese resp.setContentType("text/html;charset=UTF-8"); // Set the minimal file size DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 2); // Set the max file size ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); List<FileItem> fileItems = null; try { fileItems = upload.parseRequest(req); Iterator<FileItem> iter = fileItems.iterator(); while (iter.hasNext()) { FileItem fileItem = iter.next(); if (!fileItem.isFormField()) { String fileName = fileItem.getName(); System.out.println("fileName = " + fileName); fileItem.write(new File(uploadPath, fileName)); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3. Actually the server don't have to send message to Flex explicitly. In Flex fileReference will monitor on file upload process.
Comments:
1)May have java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileUploadException
A: Don't use UserLibrary. Copy commons-io-2.4.jar and commons-fileupload-1.3.jar into WebRoot/WEB-INF/lib folder instead.