文件上传:
项目中经常用到文件上传。
自己实现文件上传,使用文件上传组件fileupload组件
1、指定表单类型为文件上传,
enctype=”multipart/form-data”
2、提交方式必须是:post
3、表单中存在文件域元素。
需要的jar包
index.jsp
<body> <form action="${pageContext.request.contextPath}/FileUploadTest" method = "post" enctype="multipart/form-data"> 用户名::<input type = "text" name = "username"/><br> 文件:<input type = "file" name = "file1"/><br> <input type = "submit"> </form> </body>
FileUploadTest.servlet
package zck.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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; /** * Servlet implementation class FileUploadTest */ @WebServlet("/FileUploadTest") public class FileUploadTest extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public FileUploadTest() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //创建文件上传工厂类 DiskFileItemFactory fileItemFactory = new DiskFileItemFactory(); //创建文件上传核心类 ServletFileUpload upload = new ServletFileUpload(fileItemFactory); upload.setFileSizeMax(30*1024*1024);//设置单个文件最大值30M upload.setSizeMax(50*1024*1024);//最多50个文件 //判断表单是否是文件上传表单 if(upload.isMultipartContent(request)) { //把请求数据转化为FileItem对象集合 try { List<FileItem> list = upload.parseRequest(request); //遍历得到每一个数据项 for(FileItem fileItem :list) { //判断普通项,还是文件。 if(fileItem.isFormField()) { //普通表单项 String fieldName =fileItem.getFieldName();//表单元素名称 String content =fileItem.getString();//值 System.out.print(fieldName+"\n"+content+"\n\n"); }else { //文件上传表单项 String name =fileItem.getName();//获取文件名 //上传文件目录路径 String basePath = ("D:\\software\\eclipse\\workplace2019-1\\UploadFiles\\WebContent\\upload\\"); //新建文件 File file = new File(basePath,name); fileItem.write(file); fileItem.delete();//删除临时文件 } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }else { System.out.print("不是文件上传表单,不处理"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
运行界面
代码中主要对象及属性
原文:https://www.cnblogs.com/2016-zck/p/11442741.html