转载:原文连接https://blog.csdn.net/HaHa_Sir/article/details/81744629
一、前端 html 代码
<center>
<h2> 基于servelt 3.0注解实现文件上传 </h2>
<h3>1、单个文件上传</h3>
<form action="${ctx }/uploadServlet" method="post" enctype="multipart/form-data">
文件: <input type="file" name="uploadfile" ><br><br><br>
<button type="submit" >提交</button>
</form>
<hr>
<h3>2、 多个文件上传</h3>
<form action="${ctx }/uploadServlet" method="post" enctype="multipart/form-data">
文件1: <input type="file" name="uploadfile" >
文件2: <input type="file" name="uploadfile" >
文件3: <input type="file" name="uploadfile" ><br><br><br>
<button type="submit" >提交</button>
</form>
</center>
二、uploadServlet 后端上传部分代码
import java.io.File;
import java.io.IOException;
import java.util.Collection;
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;
/**
* 文件上传servlet
*/
@WebServlet("/uploadServlet")
// 该注解 将该Servlet 标记为一个文件上传的 servlet
@MultipartConfig
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1、 获取文件的存储路径
String realPath = request.getServletContext().getRealPath(File.separator+"userfiles");
File file = new File(realPath);
if(!file.exists()){
file.mkdirs();
System.out.println("路径: "+realPath +" 创建成功!");
}
// 2、获取上传文件对象的集合
Collection<Part> partList = request.getParts();
if(partList.size() == 1){
// 单个文件上传
Part part = request.getPart("uploadfile");
// 获取header 如: form-data; name="uploadfile"; filename="2018-08-11 开【华夏视讯网首发hxsxw.com】.mkv"
String header = part.getHeader("content-disposition");
// 获取文件名
String fileName = header.split(";")[2].split("=")[1].replaceAll("\"", "");
// 执行写入操作 --- 上传到指定的目录
part.write(realPath+File.separator+fileName);
}else{
for (Part part : partList) {
// 多个文件上传
String header = part.getHeader("content-disposition");
String fileName = getFileName(header);
part.write(realPath+File.separator+fileName);
}
}
request.setAttribute("message", "文件上传成功!");
request.getRequestDispatcher("/WEB-INF/views/client/message.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
/**
* 根据请求头解析出文件名
* 请求头的格式:火狐和google浏览器下:form-data; name="file"; filename="snmp4j--api.zip"
* IE浏览器下:form-data; name="file"; filename="E:\snmp4j--api.zip"
* [@param](https://my.oschina.net/u/2303379) header 请求头
* [@return](https://my.oschina.net/u/556800) 文件名
* [@see](https://my.oschina.net/weimingwei) https://www.cnblogs.com/xdp-gacl/p/4224960.html
* @date 2018年8月12日 22:57:27
*/
public String getFileName(String header) {
/**
* String[] tempArr1 = header.split(";");代码执行完之后,在不同的浏览器下,tempArr1数 组里面的内容稍有区别
* 火狐或者google浏览器下:tempArr1={form-data,name="file",filename="snmp4j--api.zip"}
* IE浏览器下:tempArr1={form-data,name="file",filename="E:\snmp4j--api.zip"}
*/
String[] tempArr1 = header.split(";");
/**
*火狐或者google浏览器下:tempArr2={filename,"snmp4j--api.zip"}
*IE浏览器下:tempArr2={filename,"E:\snmp4j--api.zip"}
*/
String[] tempArr2 = tempArr1[2].split("=");
//获取文件名,兼容各种浏览器的写法
String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\")+1).replaceAll("\"", "");
return fileName;
}
}
三、DownLoadServlet 文件下载
1、使用 response.getOutputStream(); 返回二进制数据流,实现文件下载
2、 代码如下:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 文件下载 servlet
*/
@WebServlet("/downloadServlet")
public class DownLoadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1、文件存放路径
String path="c:/";
// 2、需要下载的文件名
String fileName="default.png";
File file = new File(path+fileName);
response.reset();
response.setCharacterEncoding("UTF-8");
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
InputStream input = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int len ;
while((len = input.read(buff)) != -1){
out.write(buff, 0, len);
out.flush();
}
input.close();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}