要在Spring Boot中配置阿里云OSS存储实现文件上传下载功能,你可以按照以下步骤操作:
引入相关依赖:
在pom.xml
文件中添加以下依赖:<dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.4</version> </dependency>
配置OSS相关参数:
在application.properties
或application.yml
文件中配置阿里云OSS的accessKeyId、accessKeySecret、endpoint、bucket等参数:oss.endpoint=your_endpoint oss.accessKeyId=your_access_key_id oss.accessKeySecret=your_access_key_secret oss.bucketName=your_bucket_name
创建OSS客户端:
创建一个OSS客户端的bean,用于操作OSS:@Configuration public class OSSConfig { @Value("${oss.endpoint}") private String endpoint; @Value("${oss.accessKeyId}") private String accessKeyId; @Value("${oss.accessKeySecret}") private String accessKeySecret; @Bean public OSSClient ossClient() { return new OSSClient(endpoint, accessKeyId, accessKeySecret); } }
实现文件上传和下载的方法:
创建一个Service或Controller类,实现文件上传和下载的方法:@Service public class FileService { @Autowired private OSSClient ossClient; @Value("${oss.bucketName}") private String bucketName; public String uploadFile(String filename, InputStream inputStream) { ossClient.putObject(bucketName, filename, inputStream); // 返回文件的URL return ossClient.generatePresignedUrl(bucketName, filename, new Date(System.currentTimeMillis() + 3600 * 1000)).toString(); } public InputStream downloadFile(String filename) { OSSObject ossObject = ossClient.getObject(bucketName, filename); return ossObject.getObjectContent(); } }
调用文件上传和下载的方法:
在Controller中调用文件上传和下载的方法:@RestController public class FileController { @Autowired private FileService fileService; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { // 获取文件的输入流 InputStream inputStream = file.getInputStream(); // 生成文件名 String filename = UUID.randomUUID().toString() + file.getOriginalFilename(); // 调用文件上传方法 String fileUrl = fileService.uploadFile(filename, inputStream); return fileUrl; } @GetMapping("/download/{filename}") public ResponseEntity<InputStreamResource> downloadFile(@PathVariable("filename") String filename) throws IOException { // 调用文件下载方法 InputStream inputStream = fileService.downloadFile(filename); // 设置文件响应头 HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=" + filename); return ResponseEntity.ok() .headers(headers) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(new InputStreamResource(inputStream)); } }
以上就是在Spring Boot中配置阿里云OSS存储实现文件上传下载功能的步骤。你可以根据自己的需求进行修改和扩展。