Servlet实现文件上传
注意:
- 导jar包:commons-fileupload-xxx、commons-io-xxx.jar。
maven只引入commons-fileupload依赖即可。commons-io自动引入 - 表单 method 属性应该设置为 POST 方法,不能使用 GET 方法。
- 表单 enctype 属性应该设置为 multipart/form-data.
上传文件的servlet的dopost方法:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 判断是否分段发送,如果不是无法处理
if (!ServletFileUpload.isMultipartContent(request)) {
PrintWriter writer = response.getWriter();
writer.write("Error: 表单必须包含 enctype=multipart/form-data");
writer.flush();
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// 创建用于解析上传数据的工具类
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置中文处理编码
upload.setHeaderEncoding("utf-8");
// 设置文件夹路径 最好放在webapp外否则每次部署会清空文件夹
String uploadPath = "D:\\upload";
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
try {
// 获取表单项
List<FileItem> formItems = upload.parseRequest(request);
if (formItems != null && formItems.size() > 0) {
// 遍历表单项
for (FileItem item : formItems) {
if (item.isFormField()) {
System.out.println("请求参数名:"+item.getFieldName());
// getString 获取普通表单项的值 参数是设置编码
System.out.println("请求参数值:"+item.getString("utf-8"));
}else {
// 文件表单项
String fileName = item.getName();
String filePath = uploadPath+File.separator+fileName;
// 如果要保存路径到数据库 保存filePath即可
File storePath = new File(filePath);
// 保存的硬盘
item.write(storePath);
request.setAttribute("msg","文件上传成功");
}
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("msg", e.getMessage());
}
request.getRequestDispatcher("massage.jsp").forward(request,response);
}
参考:https://www.runoob.com/jsp/jsp-file-uploading.html
拓展:
DiskFileItemFactory类的使用:https://www.cnblogs.com/w-wfy/p/6239330.html
JAVA文件上传 ServletFileUpLoad 实例:
https://www.cnblogs.com/liuyangv/p/8298997.html
Servlet文件下载
- 主要思路是将文件以流的方式读入内存,再以流的形式写到客户端
resp.addHeader("Content-Disposition","attachment;filename=" + fileDisplay)
以附件方式发送,客户端会自动下载
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//resp.setContentType("text/html;charset=utf-8");
resp.setContentType("application/x-download");
Integer id = Integer.valueOf(req.getParameter("id"));
TFile file = fileDao.getFileById(id);
if (file == null) {
System.out.println("文件不存在");
return;
}
String fileDisplay = file.getFileName();
fileDisplay = URLEncoder.encode(fileDisplay,"utf-8");
// 将文件以附件发送客户端会自动下载
resp.addHeader("Content-Disposition","attachment;filename=" + fileDisplay);
OutputStream out = null;
InputStream in =null;
try {
in = new FileInputStream(file.getFilePath());
out = resp.getOutputStream();
byte[] b = new byte[1024];
int i = 0;
while ((i = in.read(b)) != -1) {
out.write(b,0,i);
}
out.flush();
in.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
if (in != null) {
in.close();
}
}
}