更详细,更细致的内容 参考博客 用SmartUpload实现文件上传,下载,删除
0. jar 链接地址
链接:https://pan.baidu.com/s/1rH7KhNNctF3Qsati63YNRw
提取码:yyug
复制这段内容后打开百度网盘手机App,操作更方便哦
1. 上传文件
@WebServlet(urlPatterns = "/upload", name = "upload")
public class UploadServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try{
// 1. 创建上传文件的对象
SmartUpload smartUpload = new SmartUpload();
// 2. 初始化上传操作
// 参数4 : jsp 的错误页面s
// 参数5 : 是否会使用 session
// 参数6 : 缓冲区的大小
// 参数7 :缓冲区满了是否会将内容刷新到输出流当中。
PageContext pageContext = JspFactory.getDefaultFactory().
getPageContext(this, req, resp, null, false, 1024, true);
smartUpload.initialize(pageContext);
// 2.1 设置编码防止乱码
smartUpload.setCharset("UTF-8");
// 3. 将上传的文件信息设置到 smartUpload 中。s
smartUpload.upload();
// 4. 获取文件信息
File file = smartUpload.getFiles().getFile(0);
String fileName = file.getFileName();
String contentType = file.getContentType();
String newFileName = smartUpload.getRequest().getParameter("newFileName");
fileName = newFileName + "-" + fileName;
// 5. 指定文件的上传路径
String uploadPath = "/uploadFiles/"+ URLEncoder.encode(fileName, "UTF-8");
// 6. 保存文件
file.saveAs(uploadPath, File.SAVEAS_VIRTUAL);
// 7. 跳转到成功页面
req.setAttribute("path", uploadPath);
req.getRequestDispatcher("success.jsp").forward(req, resp);
} catch (Exception e) {
req.setAttribute("errorMessage", e.getMessage());
req.getRequestDispatcher("error.jsp").forward(req, resp);
}
}
}
3. 下载文件
@WebServlet(urlPatterns = "/downing", name = "downing")
public class DownServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1. 获取文件名称
String fileName = req.getParameter("fileName");
String path = "/uploadFiles/" + fileName;
// 2. 设置响应的类型
resp.setContentType("application/octet-stream");
resp.addHeader("Content-Disposition", "attachment;filename="+fileName);
// 3. 跳转页面
req.getRequestDispatcher(path).forward(req, resp);
// 4. 清空缓存区
resp.flushBuffer();
}
}