浏览 2490 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2013-05-13
package com.panguso.phl.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; 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.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * 上传的测试代码 * * @author piaohailin * @date 2013-1-31 */ public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; // 用于存放上传文件的目录 private String uploadPath = "c:\\upload"; private File tempPath = new File("c:\\upload\\temp"); /** * @see HttpServlet#HttpServlet() */ public UploadServlet() { super(); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("UTF-8"); // 创建一个上传项目工厂,并设置其缓存数据大小和临时文件保存位置 DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4096); factory.setRepository(tempPath); // 使用项目工厂创建一个ServletFileUpload对象,用于解析文件上传请求 // 并设置可以上传的文件的最大字节数,超过会抛出异常 ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(1024 * 1024); upload.setHeaderEncoding("utf-8"); try { List<FileItem> fileItems = upload.parseRequest(request); for (FileItem fileItem : fileItems) { System.out.println(fileItem.getName()); } } catch (Exception e) { e.printStackTrace(); } } } 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |