spring boot 2.0.5
要实现文件上传并直接访问(查看/下载)
配置静态文件路径
application.properties
uploadPath=/opt/data1/uploads/
## 上传路径设置为静态资源路径,可以通过http直接访问,比如图片/pdf会直接显示在浏览器,word/excell会直接下载
spring.resources.static-locations=classpath:/META-INF/resources/, classpath:/resources/, classpath:/static/, classpath:/public/,file:${uploadPath}
上传接口
/**
* 文件上传
* @Author:sahana
*/
@RestController @Slf4j public class UploadController {
@Value("${uploadPath}") String uploadPath;//上传文件的保存路径
@PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
Path path = Paths.get(uploadPath, file.getOriginalFilename());//存储路径
Files.copy(file.getInputStream(), path);//写入
// --另一种方式
// File serverFile = new File(uploadPath+file.getOriginalFilename());
// file.transferTo(serverFile);
return "上传成功";
} catch (IOException e) {
return "上传失败";
}
} else {
return "空文件";
}
}
}