servlet实现图片上传和下载

作者 : admin 本文共1581个字,预计阅读时间需要4分钟 发布时间: 2024-06-10 共2人阅读

图片上传
前端
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();
            }
        }
    }

本站无任何商业行为
个人在线分享 » servlet实现图片上传和下载
E-->