SpringBoot 中文件的使用

default

各种文件路径

获取项目 resource 目录下的 “/static/file.txt”

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
/**
 * 方法一
 */
String path = this.getClass().getResource("/static/file.txt").getPath();
System.err.println("path:" + path);
// path:D:/project/demo/target/classes/static/file.txt
 
/**
 * 方法二
 */
String path2 = this.getClass().getClassLoader().getResource("static/file.txt").getPath();
System.err.println("path2:" + path2);
// path2:D:/project/demo/target/classes/static/file.txt

获取启动 jar 包时使用命令的路径(运行 jar 包时的 pwd 路径)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
String path3 = System.getProperty("user.dir");
System.err.println("path3:" + path3);
// path3:D:\project\demo


// 新建文件时不指定绝对路径,也是会根据执行命令的路径来存放文件
File file = new File("");
try {
	// 获取文件的绝对路径,比 absolutePath 更明确。
    // 假如新建文件时指定了 new File("../file.text"),  absolutepath 会包含 ".." 为 "D:/project/demo/../file.text"
    String path4 = file.getCanonicalPath();
    System.err.println("path4:" + path4);
} catch (IOException e) {
   e.printStackTrace();
}
// path4:D:\project\demo

对文件路径的操作

拼接路径

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// 拼接两个路径(此方法在 StringUtils 中,不建议经常对 Path 使用,会阻碍理解)
String path = "D:/data";
String relativePath = "details";
StringUtils.applyRelativePath(path, relativePath);
// "D:/data/details

// 拼接路径和带后缀的文件名
String path = "D:/data";
String fileName = "file.txt";
File file = new File(path, fileName);
// D:/data/file.txt

上传和下载

上传

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@slfj2
@RestController
public class FileUploadController {
 
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件为空");
        }
        try {
            File uploadedFile = new File("/data/upload/" + file.getOriginalFilename());
            file.transferTo(uploadedFile);
            return "File uploaded successfully!";
        } catch (IOException e) {
            log.error("文件保存失败",  ExceptionUtil.stacktraceToString(e));
            throw new RuntimeException("文件上传失败");
        }
    }
}

下载

方式一 ResponseEntity

  1. 一定要加 produces = MediaType.APPLICATION_OCTET_STREAM_VALUE
  2. 一定要加 @ResponseBody
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

@GetMapping(value = "/download/{fileName:.+}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
    Path filePath = Paths.get("/data/upload/").resolve(fileName).normalize();
    try {
        Resource resource = new org.springframework.core.io.UrlResource(filePath.toUri());
        if (resource.exists() || resource.isReadable()) {
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                    .body(resource);
        } else {
            return ResponseEntity.notFound().build();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        return ResponseEntity.status(500).build();
    }
}


@GetMapping(value = "/download/{fileName:.+}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public ResponseEntity downloadFile(@PathVariable String fileName) throws IOException {
    byte[] bytes = ...
    Resource resource = new org.springframework.core.io.UrlResource(filePath.toUri());
    return ResponseEntity.ok()
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
            .body(bytes);
}

方式二

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
@GetMapping(value = "/getFile", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ApiOperation(value = "根据id获取文件")
public void getFile(@RequestParam PoiTypeEnum type, @RequestParam Integer fileId, HttpServletResponse response) throws IOException {
    FileEntity fileEntity = getById(id);
    response.reset();
    response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
    response.setCharacterEncoding("UTF-8");
    String utf8FileName = URLEncoder.encode(fileEntity.getFileName(), StandardCharsets.UTF_8);
    response.setHeader("Content-Disposition", "attachment;filename=" + utf8FileName);

    File file = new File(systemConfig.getStoragePath(), fileEntity.getFilePath());
    try (ServletOutputStream outputStream = response.getOutputStream();
         FileInputStream fileInputStream = new FileInputStream(file);) {
        int count = 0;
        byte[] by = new byte[1024];
        //通过response对象获取OutputStream流
        while ((count = fileInputStream.read(by)) != -1) {
            outputStream.write(by, 0, count);
        }
        outputStream.flush();
    }
}
Gear(夕照)的博客。记录开发、生活,以及一些不足为道的思考……