如何在Spring Boot中实现图片上传至本地和阿里云OSS
在Spring Boot中实现图片上传至本地和阿里云OSS,你需要使用Spring的MultipartFile接口来处理上传的文件,并使用阿里云提供的SDK进行OSS操作。以下是一个简化的例子:
- 添加阿里云OSS依赖到你的
pom.xml
:
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.6.0</version>
</dependency>
- 配置阿里云OSS参数在
application.properties
或application.yml
:
# 阿里云OSS配置
aliyun.oss.endpoint=你的EndPoint
aliyun.oss.accessKeyId=你的AccessKeyId
aliyun.oss.accessKeySecret=你的AccessKeySecret
aliyun.oss.bucketName=你的BucketName
- 创建配置类来读取这些参数:
@Configuration
public class AliyunOSSConfig {
@Value("${aliyun.oss.endpoint}")
private String endpoint;
@Value("${aliyun.oss.accessKeyId}")
private String accessKeyId;
@Value("${aliyun.oss.accessKeySecret}")
private String accessKeySecret;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
@Bean
public OSS oSSClient() {
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
// Getter methods for endpoint, accessKeyId, etc.
}
- 创建Service类来处理上传逻辑:
@Service
public class ImageUploadService {
@Autowired
private OSS ossClient;
@Value("${aliyun.oss.bucketName}")
private String bucketName;
public String uploadImageToOSS(MultipartFile file) throws IOException {
String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
ossClient.putObject(bucketName, fileName, file.getInputStream());
return "https://" + bucketName + "." + ossClient.getEndpoint().getHost() + "/" + fileName;
}
public void shutdownOSSClient() {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
- 在Controller中使用Service上传图片:
@RestController
public class ImageUploadController {
@Autowired
private ImageUploadService imageUploadService;
@PostMapping("/upload")
public String uploadImage(@RequestParam("file") MultipartFile file) {
try {
return imageUploadService.uploadImageToOSS(file);
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
}
}
- 在Spring Boot启动类中添加关闭OSS客户端的Hook:
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(Strin
评论已关闭