JavaWeb中文件上传和下载的一些方法
1.前端支持
前端的form表单必须multipart-formdata复杂类型的表单,必须是POST请求
<form action="/upload" method="post" enctype="multipart/form-data">
请选择:<input name="file" type="file"/><br> <input type="submit" value="上传"/></form>
2.文件上传使用原生Servlet
使用HttpServletRequest接收上传文件,Servlet3.0
package cn.yu.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Collection;
import java.util.UUID;
@WebServlet(value = "/upload")
@MultipartConfig
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获得上传路径
String uploadPath = req.getSession().getServletContext().getRealPath("/upload/");
// 2.创建路径
File path = new File(uploadPath);
if (!path.exists()) path.mkdirs();
//3.接收表单数据
Collection<Part> parts = req.getParts();
File upload = null;
BufferedInputStream in = null;
BufferedOutputStream out = null;
byte[] bs = null;
int len = 0;
for (Part part : parts){
// 如果内容类型不是null 那么就是文件
if (part.getContentType() != null){
// 获得文件名
String fileName = part.getSubmittedFileName();
// 生成UUID
String uuid = UUID.randomUUID().toString();
fileName = uuid + "_" + fileName;
// 创建上传的文件
upload = new File(uploadPath+fileName);
upload.createNewFile();
// 获取输入流
in = new BufferedInputStream(part.getInputStream());
bs = new byte[2048];
// 定义输出流
out = new BufferedOutputStream(new FileOutputStream(upload));
// 写入文件
while ((len = in.read(bs)) != -1){
out.write(bs,0,len);
out.flush();
}
in.close();
out.close();
}
}
resp.sendRedirect("/success.html");
}
}
PS:在使用Part这个对象的时候,需要配置@MultipartConfig注解
3.文件下载HtppServletResponse
使用HttpServletResponse对象,响应客户端的文件下载请求
package cn.yu.servlet;
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 java.io.*;
@WebServlet(value = "/download")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取文件上传目录的路径
String path = req.getSession().getServletContext().getRealPath("/upload/");
// 2.获取文件名
String filename = req.getParameter("filename");
// 3.定义输入流和输出流
BufferedOutputStream out = null;
BufferedInputStream in = null;
File download = new File(path + filename);
// 4.获得文件
in = new BufferedInputStream(new FileInputStream(download));
// 5.设置响应头
resp.setHeader("Content-disposition","attachment;filename=" + filename);
resp.setContentLengthLong(download.length());
// 6.向客户端输出文件
out = new BufferedOutputStream(resp.getOutputStream());
byte[] bs = new byte[2048];
int len = -1;
while ((len = in.read(bs)) != -1){
out.write(bs,0,len);
out.flush();
}
in.close();
out.close();
}
}
注意:响应头必须是Content-disposition:attachment;filename=filename
4.使用ServletFileUpload接收上传文件
package cn.yu.servlet1;
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 javax.servlet.ServletConfig;
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 java.io.*;
import java.util.List;
import java.util.UUID;
@WebServlet(value = "/upload1")
public class UploadServlet1 extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取上传路径
String uploadPath = req.getSession().getServletContext().getRealPath("/upload/");
// 2.创建路径
File path = new File(uploadPath);
if(!path.exists()) path.mkdirs();
// 3.创建磁盘文件项工厂对象
DiskFileItemFactory factory = new DiskFileItemFactory();
// 4.创建文件上传的servlet
ServletFileUpload upload = new ServletFileUpload(factory);
File ufile = null;
BufferedOutputStream out = null;
try {
// 5.解析上传的文件的请求 获取表单项文件项的集合
List<FileItem> items = upload.parseRequest(req);
// 6.遍历集合
for (FileItem item: items){
// 7.判断是否为普通表单项
if (item.isFormField()){
}else {
byte[] bs = new byte[2048];
int len = -1;
//8. 获取文件名
String fileName = item.getName();
String uuid = UUID.randomUUID().toString();
fileName = uuid + "_" + fileName;
ufile = new File(uploadPath + fileName);
// 获取文件的输入流
InputStream in = item.getInputStream();
// 创建输出流
out = new BufferedOutputStream(new FileOutputStream(ufile));
while ((len = in.read(bs)) != -1){
out.write(bs,0,len);
out.flush();
}
in.close();
out.close();
bs = null;
}
}
resp.sendRedirect("/success.html");
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
在使用FileUploadServlet的时候需要提供apache的Commons-fileupload包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
5.使用Commons-IO简化IO操作
Maven依赖
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
文件上传
package cn.yu.servlet1;
import org.apache.commons.io.IOUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.util.Collection;
import java.util.UUID;
@WebServlet(value = "/upload2")
@MultipartConfig
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取文件上传的路径
String uploadPath = req.getSession().getServletContext().getRealPath("/upload/");
// 2.创建路径
File path = new File(uploadPath);
if (! path.exists()) path.mkdirs();
// 3.定义文件输出流
BufferedOutputStream out = null;
// 4.获取表单项
Collection<Part> parts = req.getParts();
// 5.遍历表单项
for (Part part : parts){
// 判断是否为文件项
if (part.getContentType() != null){
// 获取文件名
String fileName = part.getSubmittedFileName();
String uuid = UUID.randomUUID().toString();
fileName = uuid + "_" + fileName;
// 获取文件输入流
InputStream in = part.getInputStream();
// 创建文件的输出流
out = new BufferedOutputStream(new FileOutputStream(uploadPath + fileName));
IOUtils.copy(in,out);
in.close();
out.close();
}
}
resp.sendRedirect("/success.html");
}
}
文件下载
package cn.yu.servlet;
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 java.io.*;
@WebServlet(value = "/download")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1.获取文件上传目录的路径
String path = req.getSession().getServletContext().getRealPath("/upload/");
// 2.获取文件名
String filename = req.getParameter("filename");
// 3.定义输入流和输出流
BufferedOutputStream out = null;
BufferedInputStream in = null;
File download = new File(path + filename);
// 4.获得文件
in = new BufferedInputStream(new FileInputStream(download));
// 5.设置响应头
resp.setHeader("Content-disposition","attachment;filename=" + filename.substring(filename.indexOf("_")));
resp.setContentLengthLong(download.length());
// 6.向客户端输出文件
out = new BufferedOutputStream(resp.getOutputStream());
org.apache.commons.io.IOUtils.copy(in,out);
in.close();
out.close();
}
}