文件上传FileUpload
Posted MrPeng
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了文件上传FileUpload相关的知识,希望对你有一定的参考价值。
从上面可以看出,如果我们想上传文件,需要对表单提交过来的内容进行解析,每一个文件项.
java 核心代码
jar 包
文件上传代码
package cn.ecit.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; 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.FileItemFactory; 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{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //初始化文件工厂 FileItemFactory fileItemFactory = new DiskFileItemFactory(); ServletFileUpload up = new ServletFileUpload(fileItemFactory); up.setFileSizeMax(50*1024*1024); up.setSizeMax(10*1024*1024); up.setHeaderEncoding("UTF-8"); if(up.isMultipartContent(req)){ try { List<FileItem> list = up.parseRequest(req); for(FileItem item:list){ if(item.isFormField()){ String fieldName = item.getFieldName(); String fieldValue = item.getString("UTF-8"); System.out.println(fieldName+" "+fieldValue); }else{ String fileName = item.getName(); String path = getServletContext().getRealPath("/upload"); File file = new File(path,fileName); item.write(file); item.delete(); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
文件上传总结:
1.创建文件临时工厂
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload up = new ServletFileUpload(factory);
2.配置工厂参数
up.setFileSizeMax(30*1024*1024);
up.setSizeMax(80*1024*1024);
up.setHeaderEncoding("UTF-8");
3.判断是否为文件上传(由前台提交表单属性决定)
up.isMultipartContent(req)
4.得到 FileItem (可以是多文件上传)
List<FileItem> list = up.parseRequest(req);
一个list 代表一个文件项目,如上图所示
5.遍历文件项
for(FileItem item:list)
6.判断 item.isFormField() 是否为普通文本框
7. 得到文件上传路径 getServletContext().getRealPath("/upload");
8.写入文件 item.write(file);
9.item.delete(); 删除临时文件
以上是关于文件上传FileUpload的主要内容,如果未能解决你的问题,请参考以下文章