Flex+java实现文件上传

用了两天时间学习了下Flex和java配合实现文件上传,找了个小例子。前端当然是flex,后台使用servlet,把代码贴上来,备忘吧:

 

FileUpload.java:

import java.io.File; import java.io.IOException; import java.io.PrintWriter; 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; @SuppressWarnings("serial") public class FileUpload extends HttpServlet { //定义文件上传的路径 private String uploadPath = "d://a//"; private int maxPostSize = 100*1024*1024; public FileUpload() { super(); } public void destroy() { super.destroy(); } @SuppressWarnings("unchecked") protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { System.out.println("Access!"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.print("已连接上!"); //保存文件到服务器中 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(maxPostSize); try { List fileItems = upload.parseRequest(request); Iterator iter = fileItems.iterator(); while(iter.hasNext()) { FileItem item = (FileItem)iter.next(); if(!item.isFormField()) { String name = item.getName(); System.out.println(name); try { item.write(new File(uploadPath+name)); } catch(Exception e) { e.printStackTrace(); } } } } catch(FileUploadException e) { e.printStackTrace(); System.out.println(e.getMessage()+"结束"); } } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }

 

FileUpload.mxml

 

配置到tomcat上的时候,要在web-inf/lib里面要加入连个包:

  1. commons-fileupload-1.2.1.jar
  2. commons-io-1.4.jar

这两个包在网上很容易下载到。加入包以后要修改web.xml,在跟下加入下面servlet声明:

FileUpload FileUpload FileUpload /servlet/FileUpload

我的文件是上传到D盘的a文件夹,要确保该目录存在。上传个图片试试吧!

你可能感兴趣的:(Flex)