在 pom.xml
文件中添加以下依赖:
<dependency>
<groupId>com.aliyun.ossgroupId>
<artifactId>aliyun-sdk-ossartifactId>
<version>3.11.0version>
dependency>
在 application.yml
文件中添加阿里云 OSS 的配置信息:
aliyun:
oss:
endpoint: -endpoint>
access-key-id: -access-key-id>
access-key-secret: -access-key-secret>
bucket-name: -bucket-name>
上传文件的接口可以通过 MultipartFile
来接收上传的文件,然后调用阿里云 OSS 的 API 将文件上传到 OSS 上。
@RestController
public class FileUploadController {
@Autowired
private OSSClient ossClient;
@Value("${aliyun.oss.bucket-name}")
private String bucketName;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
ossClient.putObject(bucketName, fileName, inputStream);
return "Upload file " + fileName + " success";
}
}
下载文件的接口可以通过调用阿里云 OSS 的 API 将文件下载到本地,然后将文件写入输出流返回给客户端。
@RestController
public class FileDownloadController {
@Autowired
private OSSClient ossClient;
@Value("${aliyun.oss.bucket-name}")
private String bucketName;
@GetMapping("/download")
public void downloadFile(@RequestParam("file") String fileName, HttpServletResponse response) throws IOException {
OSSObject ossObject = ossClient.getObject(bucketName, fileName);
InputStream inputStream = ossObject.getObjectContent();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
}
查看文件的接口可以通过调用阿里云 OSS 的 API 获取文件的 URL,然后将 URL 返回给客户端。
@RestController
public class FileViewController {
@Autowired
private OSSClient ossClient;
@Value("${aliyun.oss.bucket-name}")
private String bucketName;
@GetMapping("/view")
public String viewFile(@RequestParam("file") String fileName) {
Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
return url.toString();
}
}
删除文件的接口可以通过调用阿里云 OSS 的 API 删除指定的文件。
@RestController
public class FileDeleteController {
@Autowired
private OSSClient ossClient;
@Value("${aliyun.oss.bucket-name}")
private String bucketName;
@DeleteMapping("/delete")
public String deleteFile(@RequestParam("file") String fileName) {
ossClient.deleteObject(bucketName, fileName);
return "Delete file " + fileName + " success";
}
}
注意:以上代码中的 OSSClient
在新版的 SDK 中已经被废弃,可以使用 OSS
接口来代替。例如:
@Autowired
private OSS oss;
oss.putObject(bucketName, fileName, inputStream);
另外本项目的源码都在gitee中 https://gitee.com/ZheShuCheng/case 如果对你有帮助请点击start哦 谢谢