利用springbboot和oss存储图片前端不要application.properties
时间: 2023-06-17 12:02:39 浏览: 70
在使用Spring Boot和OSS存储图片时,可以考虑使用YAML文件来代替application.properties文件。以下是一个示例:
首先,在pom.xml文件中添加如下依赖:
```xml
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
```
然后,在application.yml文件中添加以下内容:
```yaml
# OSS配置
oss:
endpoint: oss-cn-hangzhou.aliyuncs.com
access-key-id: your_access_key_id
access-key-secret: your_access_key_secret
bucket-name: your_bucket_name
object-prefix: your_object_prefix
```
接下来,在Java代码中使用该配置:
```java
@Configuration
@ConfigurationProperties(prefix = "oss")
public class OSSConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private String objectPrefix;
// 省略getter和setter方法
@Bean
public OSSClient ossClient() {
return new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
@Bean
public OSSService ossService(OSSClient ossClient) {
return new OSSServiceImpl(ossClient, bucketName, objectPrefix);
}
}
```
在上述代码中,使用@ConfigurationProperties注解将配置文件中oss前缀的属性注入到OSSConfig类中,然后将OSSClient和OSSService注入到Spring容器中。
最后,在Java代码中使用OSSService将图片上传到OSS:
```java
@RestController
public class ImageController {
@Autowired
private OSSService ossService;
@PostMapping("/images")
public String uploadImage(@RequestParam("file") MultipartFile file) {
String fileName = file.getOriginalFilename();
String objectName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(fileName);
try {
ossService.upload(objectName, file.getInputStream());
return ossService.getObjectUrl(objectName);
} catch (IOException e) {
throw new RuntimeException("Failed to upload image", e);
}
}
}
```
在上述代码中,使用@RequestParam注解从HTTP请求中获取上传的图片文件,然后将其上传到OSS中,并返回图片的URL。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)