Spring Boot文件上传与下载的实现

Spring Boot文件上传后端代码实现:

@PostMapping
public FileInfo upload(MultipartFile file) throws IOException {

    System.out.println("fileName: " + file.getName());
    System.out.println("originalFilename: " + file.getOriginalFilename());
    System.out.println("fileSize" + file.getSize());
    File localFile = new File(folder + System.currentTimeMillis() + ".txt");
    file.transferTo(localFile);
    return new FileInfo(localFile.getAbsolutePath());
}

Spring Boot文件下载后端代码实现

@GetMapping("/{id}")
public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) {
    try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
         OutputStream outputStream = response.getOutputStream()){
        response.setContentType("application/x-download");
        response.addHeader("Content-Disposition", "attachment;filename=test.txt");
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

你可能感兴趣的:(javaweb,spring,boot,文件上传与下载)