smartupload 文件上传

更详细,更细致的内容 参考博客 用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();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值