时间:2020-10-18 14:16:53 | 栏目:JAVA代码 | 点击:次
一、文件上传原理
1、文件上传的前提:
a、form表单的method必须是post
b、form表单的enctype必须是multipart/form-data(决定了POST请求方式,请求正文的数据类型)
c、form中提供input的type是file类型的文件上传域
二、利用第三方组件实现文件上传
1、commons-fileupload组件:
jar:commons-fileupload.jar
commons-io.jar
2、核心类或接口
DiskFileItemFactory:设置环境
public void setSizeThreshold(int sizeThreshold) :设置缓冲区大小。默认是10Kb。
当上传的文件超出了缓冲区大小,fileupload组件将使用临时文件缓存上传文件
public void setRepository(java.io.File repository):设置临时文件的存放目录。默认是系统的临时文件存放目录。
ServletFileUpload:核心上传类(主要作用:解析请求的正文内容)
boolean isMultipartContent(HttpServletRequest?request):判断用户的表单的enctype是否是multipart/form-data类型的。
List parseRequest(HttpServletRequest request):解析请求正文中的内容
setFileSizeMax(4*1024*1024);//设置单个上传文件的大小
upload.setSizeMax(6*1024*1024);//设置总文件大小
FileItem:代表表单中的一个输入域。
boolean isFormField():是否是普通字段
String getFieldName:获取普通字段的字段名
String getString():获取普通字段的值
InputStream getInputStream():获取上传字段的输入流
String getName():获取上传的文件名
实例:先在WEB-INF目录下建一个files文件夹,也就是文件都要上传到这里,也是避免其他人直接访问
1.获取files的真实路径
String storePath = getServletContext().getRealPath("/WEB-INF/files");
2.设置环境
DiskFileItemFactory factory = new DiskFileItemFactory();//用默认的缓存和临时文件存储的地方
3.判断表单传送方式
boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) { System.out.println("上传方式错误!"); return; }
4.文件上传核心类
ServletFileUpload upload = new ServletFileUpload(factory);5.解析 //解析 List<FileItem> items = upload.parseRequest(request); for(FileItem item: items) { if(item.isFormField()){//普通字段,表单提交过来的 String fieldName = item.getFieldName();//表单信息的字段名 String fieldValue = item.getString(); //表单信息字段值 System.out.println(fieldName+"="+fieldValue); }else//文件处理 { InputStream in = item.getInputStream(); //上传文件名 C:\Users\Administrator\Desktop\a.txt String name = item.getName(); //只需要 a.txt String fileName = name.substring(name.lastIndexOf("\\")+1); //构建输出流 String storeFile = storePath+"\\"+fileName;//上传文件的保存地址 OutputStream out = new FileOutputStream(storeFile); byte[] b = new byte[1024]; int len = -1; while((len=in.read(b))!=-1) { out.write(b, 0, len); } in.close();//关闭流 out.close(); } }
写一个表单
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP '1.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="${pageContext.request.contextPath}/servlet/UploadServlet2" method="post" enctype="multipart/form-data"> 用户名<input type="text" name="username"/> <br/> <input type="file" name="f1"/><br/> <input type="file" name="f2"/><br/> <input type="submit" value="保存"/> </form> </body> </html>
写一个提交servlet:UploadServlet2
package com.liuzhen.upload; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; 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.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; //文件上传入门案例 public class UploadServlet2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编码 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); try { //上传文件的路?? String storePath = getServletContext().getRealPath("/WEB-INF/files"); //设置环境 DiskFileItemFactory factory = new DiskFileItemFactory(); //判断表单传送方式 form enctype=multipart/form-data boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) { System.out.println("上传方式错误!"); return; } ServletFileUpload upload = new ServletFileUpload(factory); //解析 List<FileItem> items = upload.parseRequest(request); for(FileItem item: items) { if(item.isFormField()){//普通字段,表单提交过来的 String fieldName = item.getFieldName();//表单信息的字段名 String fieldValue = item.getString(); //表单信息字段值 System.out.println(fieldName+"="+fieldValue); }else//文件处理 { InputStream in = item.getInputStream(); //上传文件名 C:\Users\Administrator\Desktop\a.txt String name = item.getName(); //只需要 a.txt String fileName = name.substring(name.lastIndexOf("\\")+1); //构建输出流 String storeFile = storePath+"\\"+fileName;//上传文件的保存地址 OutputStream out = new FileOutputStream(storeFile); byte[] b = new byte[1024]; int len = -1; while((len=in.read(b))!=-1) { out.write(b, 0, len); } in.close();//关闭流 out.close(); } } } catch (FileUploadException e) { throw new RuntimeException(e); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
上传的文件是在Tomcat应用中。