思路
- 上传:文件通过
MultipartFile
接收 - 下载:返回类型为
ResponseEntity<Resource>
,spring boot才能能够正确转化
代码
package top.sidian123.blog.media;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.sidian123.blog.Utils.Status;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@RestController
@RequestMapping("/image")
public class ImageController {
@Autowired
ImageService imageService;
static Logger logger= LogManager.getLogger();
@GetMapping("/{id}")
public ResponseEntity<Resource> get(@PathVariable int id){
Image image=imageService.get(id);
if(image==null){
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,"attachment;filename=\""+URLEncoder.encode(image.getName(), StandardCharsets.UTF_8)+"\"")
.header(HttpHeaders.CONTENT_TYPE,MediaType.APPLICATION_OCTET_STREAM_VALUE)
.body(new InputStreamResource(image.content));
}
@PostMapping("/upload")
public Status upload(@RequestParam MultipartFile file){
Image image=new Image();
image.setName(file.getOriginalFilename());
try {
image.setContent(file.getInputStream());
} catch (IOException e) {
logger.catching(e);
return Status.from(301,"读取失败");
}
imageService.store(image);
return Status.from(0,"ok",image.id);
}
}