springboot 上传和下载文件接口

上传文件

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResultVO upload(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            upload(file);
            return ResultVOUtil.success();
        }
        return ResultVOUtil.error(-1, "文件不能为空");
    }
    
    private void upload(MultipartFile file) {
        String path = "xxxx";
        File newFile = new File(path + "/" + file.getOriginalFilename());
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

下载文件

 	@RequestMapping("/download/{fileName}")
    public void getItemImages(HttpServletRequest request, HttpServletResponse response,
                              @PathVariable("fileName") String fileName) throws IOException {
         download(request, response, fileName);
    }


    void download(HttpServletRequest request, HttpServletResponse response, String fileName) throws IOException {
        String downloadPath = this.filePath +"/"+ fileName;
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        response.setHeader("Content-Length", String.valueOf(new File(downloadPath).length()));
        request.setCharacterEncoding("UTF-8");

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(downloadPath));
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        byte[] buff = new byte[2048];
        int bytesRead;
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
        bis.close();
        bos.close();
    }
相关推荐
©️2020 CSDN 皮肤主题: 游动-白 设计师:白松林 返回首页