commons-flieupload进行多文件上传的代码

来源:互联网 发布:大数据平台的优势 编辑:程序博客网 时间:2024/06/08 07:45

1.首先我们先看服务器端的代码:

@WebServlet("/multiupload")public class MultiUpload extends HttpServlet {private static final long serialVersionUID = 1L;protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {PrintWriter out = response.getWriter();// 存放文件基路径String basePath = "E:\\temp\\";// 判定是否为文件上传的请求if (!ServletFileUpload.isMultipartContent(request)) {out.print("is not multipartContent request");out.close();return;}//DiskFileItemFactory factory = new DiskFileItemFactory();factory.setSizeThreshold(4 * 1024);ServletFileUpload upload = new ServletFileUpload(factory);// 设置字符集,防止文件名乱码upload.setHeaderEncoding("UTF-8");InputStream is = null;OutputStream fos = null;try {List<FileItem> fileList = upload.parseRequest(request);for (FileItem fileItem : fileList) {// 不是文本字段即文件表单项,从而进行IO操作if (!fileItem.isFormField()) {String fileName = fileItem.getName();if (fileName.length() <= 0 || "".equals(fileName.trim())) {continue;}is = fileItem.getInputStream();fos = new FileOutputStream(basePath + fileName);IOUtils.copy(is, fos);fos.close();is.close();}}} catch (FileUploadException e) {System.out.println(e.getMessage());} finally {out.close();}}}


2.接下来给出视图层中相应的测试表单

<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><form name="myform"action="${pageContext.request.contextPath}/multiupload" method="post"enctype="multipart/form-data">Your name: <br> <input type="text" name="name" size="15"><br>File1:<br> <input type="file" name="myfile1"><br> <br>File2:<br> <input type="file" name="myfile2"><br> <br><input type="submit" name="submit" value="Commit"></form></body></html>

3.测试的结果是我所选择的两个文件写入到我的相应的文件加下("E:\temp\"),

4.当然在后台可以将该多个文件进行压缩打包,但是这已经不在我们讨论范围之内了。。。

0 0