SpringBoot 上传和下载文件

一个项目中用到的小功能demo,请忽视代码中的业务逻辑

上传文件

@Value("${pdf.path}")
private String path;

@RequestMapping(value = "/upload",method = RequestMethod.POST)
    public RespBean upload(MultipartFile file, Questionnaire questionnaire) {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffixName;
        try {
            file.transferTo(new File(path+fileName));
            questionnaire.setCreateTime(new Date());
            questionnaire.setPdfPath(path+fileName);
            questionnaireService.addQuestionnaire(questionnaire);

        } catch (Exception e) {
            e.printStackTrace();
            return RespBean.error("添加失败");
        }
        return RespBean.ok("添加成功");
    }

下载文件

@RequestMapping(value = "downloadPDF" ,method = RequestMethod.GET)
    public ResponseEntity<byte[]> downloadPDF(int id) throws IOException {
        // 读取pdf文件到字节里
        Questionnaire questionnaire = questionnaireService.getQuestionnaireById(id);

        if(questionnaire.getPdfPath()!=null) {
            Path path = Paths.get(questionnaire.getPdfPath());
            byte[] contents = Files.readAllBytes(path);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType("application/pdf"));
            String fileName = "output.pdf";
            headers.add("content-disposition", "inline;filename=" + fileName);
            headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
            ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
            return response;
        }
        return null;


    }

说明:

  1. ${pdf.path}是配置在application.properties中的属性,根据操作系统的不同而有所区别,比如:
# windows
pdf.path=E://
# linux
# path=/usr/local/temp

你可能感兴趣的:(后端)