servlet fileupload上传文件
程序员文章站
2022-05-25 23:13:58
...
版权信息: 可以任意转载, 转载时请务必以超链接形式标明文章原文出处, 即下面的声明.
原文出处:http://tbwuming.iteye.com/admin/blogs/1520140
1. maven依赖
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency>
2. fileload处理类
import java.io.File; import java.io.PrintWriter; import java.util.List; import javax.servlet.http.HttpServletRequest; 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; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class FileUpload { private static final Logger logger = LoggerFactory.getLogger(FileUpload.class); private static final int DEFAULT_SIZE_THRESHOLD = 1 * 1024 * 1024; private static final long DEFAULT_MAX_FILE_SIZE = 8 * 1024 * 1024; private String uploadPath; private String tempPath; private Integer thresholdSize; private Long maxFileSize; private ServletFileUpload upload; // 初始化fileload public void init() { DiskFileItemFactory diskFactory = new DiskFileItemFactory(); // 设置文件大小超过缓存时所存放的目录 diskFactory.setRepository(new File(tempPath)); // 设置缓存大小 if (thresholdSize == null) diskFactory.setSizeThreshold(DEFAULT_SIZE_THRESHOLD); else diskFactory.setSizeThreshold(thresholdSize); upload = new ServletFileUpload(diskFactory); // 设置最大可上传的文件大小 if (maxFileSize == null) upload.setSizeMax(DEFAULT_MAX_FILE_SIZE); else upload.setSizeMax(maxFileSize); } // 获取文件列表 @SuppressWarnings("unchecked") public List<FileItem> getFileItems(HttpServletRequest request) { List<FileItem> fileItems = null; try { fileItems = (List<FileItem>) upload.parseRequest(request); } catch (FileUploadException e) { logger.error("process upload request error", e); } return fileItems; } public File process(PrintWriter out, FileItem item, Throwable throwable) { String filename = item.getName(); logger.info("full filename:" + filename); if (StringUtils.isBlank(filename)) { logger.warn("filename {} is null", filename); return null; } // linux和windows路径分隔符不一样,因此处理 int index = filename.lastIndexOf("/"); if (index == -1) index = filename.lastIndexOf("\\"); // 获取文件名 filename = filename.substring(index + 1, filename.length()); long fileSize = item.getSize(); if (StringUtils.isBlank(filename) || fileSize == 0) { logger.warn("filename {} is empty", filename); return null; } // 写文件 String pathname = uploadPath + "/" + filename; File uploadFile = new File(pathname); try { item.write(uploadFile); } catch (Exception e) { throwable = e; logger.error("write file error, file={}", pathname, e); } out.println(filename + " file upload complete ..."); out.println("file size:" + fileSize + "\r\n"); return uploadFile; } public void setUploadPath(String uploadPath) { this.uploadPath = uploadPath; } public void setTempPath(String tempPath) { this.tempPath = tempPath; } public void setThresholdSize(Integer thresholdSize) { this.thresholdSize = thresholdSize; } public void setMaxFileSize(Long maxFileSize) { this.maxFileSize = maxFileSize; } }
3. servlet
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.slf4j.Logger; import org.slf4j.LoggerFactory; public class UploadServlet extends HttpServlet { private static final long serialVersionUID = -5562457977157562484L; private static final Logger logger = LoggerFactory.getLogger(UploadServlet.class); private FileUpload fileUpload; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain;charset=utf-8"); PrintWriter out = response.getWriter(); List<FileItem> fileItems = (List<FileItem>) fileUpload.getFileItems(request); for (FileItem item : fileItems) { if (!item.isFormField()) { Throwable throwable = null; fileUpload.process(out, item, throwable); } } logger.info("upload file success"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void setFileUpload(FileUpload fileUpload) { this.fileUpload = fileUpload; } }
4. html 内容
<html> <head> <title>上传文件</title> </head> <body> <center> <form name="uploadForm" method="post" enctype="multipart/form-data" action="/upload"> <table> <tr> <th colspan="2"> 上传文件 </th> </tr> <tr> <td> Upload File: </td> <td> <input type="file" name="uploadFilename" size="30"/> </td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" name="submit" value="上传"> <input type="reset" name="reset" value="重置"> </td> </tr> </form> </center> </body> </html>
说明:
1). form提交模式需要是post模式,当页面传输内容比较大的时候一般时候post方式
2). 指明enctype为multipart/form-data类型
3). action中指定servlet访问相对路径
5. spring配置
<bean class="com.taobao.crawler.web.UploadServlet"> <property name="fileUpload" ref="fileUpload" /> </bean> <bean id="fileUpload" class="com.taobao.crawler.web.FileUpload" init-method="init"> <property name="uploadPath" value="./config" /> <property name="tempPath" value="./temp" /> </bean>