使用springboot 华为云OBS上传MultipartFile
时间: 2023-10-24 16:32:31 浏览: 522
华为云OBS的上传下载删除的工具类
你可以使用 Spring Boot 和华为云 OBS SDK 来上传 MultipartFile 对象到华为云 OBS。下面是一个示例代码:
1. 首先,你需要在 pom.xml 文件中添加华为云 OBS 的依赖:
```xml
<dependency>
<groupId>com.obs</groupId>
<artifactId>obs-sdk-java</artifactId>
<version>3.20.0</version>
</dependency>
```
2. 然后,你需要配置华为云 OBS 的相关信息,如 accessKey、secretKey、endpoint 等。你可以将这些信息放在 application.properties 或 application.yml 文件中,如:
```yaml
huawei:
obs:
accessKey: yourAccessKey
secretKey: yourSecretKey
endpoint: yourEndpoint
bucketName: yourBucketName
```
3. 接下来,创建一个 Service 类来处理文件上传的逻辑:
```java
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectRequest;
import java.io.IOException;
@Service
public class ObsService {
@Value("${huawei.obs.accessKey}")
private String accessKey;
@Value("${huawei.obs.secretKey}")
private String secretKey;
@Value("${huawei.obs.endpoint}")
private String endpoint;
@Value("${huawei.obs.bucketName}")
private String bucketName;
public void uploadFile(MultipartFile file) throws IOException {
ObsClient obsClient = new ObsClient(accessKey, secretKey, endpoint);
PutObjectRequest request = new PutObjectRequest(bucketName, file.getOriginalFilename(), file.getInputStream());
obsClient.putObject(request);
obsClient.close();
}
}
```
4. 最后,在你的 Controller 中使用 ObsService 类来处理文件上传请求:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
public class FileUploadController {
@Autowired
private ObsService obsService;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
obsService.uploadFile(file);
return "File uploaded successfully.";
} catch (IOException e) {
return "Failed to upload file.";
}
}
}
```
以上就是使用 Spring Boot 和华为云 OBS SDK 上传 MultipartFile 的示例代码。确保你已经正确配置了华为云 OBS 的相关信息,并根据你的实际情况进行修改。
阅读全文