书写springboot问价上传和下载的代码
时间: 2024-05-05 16:21:16 浏览: 4
上传文件的代码示例:
```java
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
// 获取文件名
String fileName = file.getOriginalFilename();
// 创建文件
File dest = new File("上传文件存储路径/" + fileName);
// 写入文件
file.transferTo(dest);
return "上传成功";
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
}
```
下载文件的代码示例:
```java
@GetMapping("/download/{fileName}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
// 获取文件路径
Path path = Paths.get("上传文件存储路径/" + fileName);
Resource resource;
try {
// 创建Resource对象
resource = new UrlResource(path.toUri());
} catch (MalformedURLException e) {
e.printStackTrace();
return ResponseEntity.notFound().build();
}
// 设置响应头
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType("application/octet-stream"))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
```
其中,`@PostMapping("/upload")` 注解表示上传文件的接口,`@RequestParam("file")` 注解表示接收上传的文件,`@GetMapping("/download/{fileName}")` 注解表示下载文件的接口,`@PathVariable String fileName` 表示接收文件名。上传文件时通过 MultipartFile 类型的参数获取文件,然后将其写入到指定路径中;下载文件时需要通过 Resource 对象获取文件并设置响应头,然后将其作为响应体返回。