servlet实现图片上传和下载

图片上传
前端
在这里插入图片描述
后端

protected void dopost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        Part filePart = request.getPart("file"); // 获取上传的文件
        String fileName = filePart.getSubmittedFileName(); // 获取文件名

        // 将文件保存到指定位置
        File uploads = new File(request.getServletContext().getRealPath("/img"));
        File file = new File(uploads, fileName);
        try (InputStream input = filePart.getInputStream();
             OutputStream output = new FileOutputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = input.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
        }
        }

注意:
需要再servlet类上加上注解
File uploads = new File(request.getServletContext().getRealPath(“/img”));
/img为web目录下img目录

@MultipartConfig(maxFileSize = 5*1024*1024)

否则会出现
Part filePart = request.getPart(“file”);
获取为null


图片下载

 protected void dopost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path=request.getParameter("src");
        path = path.substring(4, path.length());
        String imageFilePath = request.getServletContext().getRealPath("/img") + "\\" + path; // 图片文件路径

        File imageFile = new File(imageFilePath);

        if (!imageFile.exists()) {
            response.getWriter().write("File not found");
            return;
        }
        response.setContentType("image/jpeg");
        response.setHeader("Content-Disposition", "attachment; filename=\""+path+ "\"");
        //获取下载文件的输入流
        FileInputStream in = null;
        ServletOutputStream out = null;
        try {
            in = new FileInputStream(imageFile);
            //创建缓冲区域
            int len = 0;
            byte[] buffer = new byte[1024];
            //获取输出流
            out = response.getOutputStream();
            while ((len=in.read(buffer)) > 0){
                out.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null){
                in.close();
            }
            if (out != null){
                out.close();
            }
        }
    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值