Springboot+vue+elemefe上传图片到七牛云
时间: 2023-12-22 09:05:27 浏览: 136
1. 首先,需要在七牛云上创建一个存储空间,并获取该存储空间的accessKey、secretKey、bucket和domain。
2. 在Springboot中引入七牛云的Java SDK,可以通过Maven或Gradle进行引入。例如,在Maven中添加以下依赖:
```
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>
```
3. 创建一个七牛云的配置类,用于存储accessKey、secretKey、bucket和domain等配置信息。
```
@Configuration
public class QiniuConfig {
@Value("${qiniu.accessKey}")
private String accessKey;
@Value("${qiniu.secretKey}")
private String secretKey;
@Value("${qiniu.bucket}")
private String bucket;
@Value("${qiniu.domain}")
private String domain;
@Bean
public Auth auth() {
return Auth.create(accessKey, secretKey);
}
@Bean
public Configuration configuration() {
return new Configuration(Zone.zone0());
}
@Bean
public UploadManager uploadManager() {
return new UploadManager(configuration());
}
@Bean
public BucketManager bucketManager() {
return new BucketManager(auth(), configuration());
}
@Bean
public StringMap putPolicy() {
StringMap putPolicy = new StringMap();
putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"name\":\"$(fname)\",\"size\":$(fsize)}");
return putPolicy;
}
@Bean
public String uploadToken() {
return auth().uploadToken(bucket, null, 3600, putPolicy());
}
@Bean
public String domain() {
return domain;
}
}
```
4. 在Vue中使用element-ui的上传组件,设置上传的接口为Springboot的接口。
```
<el-upload
class="upload-demo"
action="/api/upload"
:show-file-list="false"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:headers="{Authorization: 'Bearer ' + token}"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
```
5. 在Springboot中编写上传接口,在该接口中使用七牛云的Java SDK进行上传。
```
@RestController
@RequestMapping("/api")
public class UploadController {
@Autowired
private UploadManager uploadManager;
@Autowired
private String uploadToken;
@Autowired
private String domain;
@PostMapping("/upload")
public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) throws IOException {
try {
Response response = uploadManager.put(file.getBytes(), null, uploadToken);
if (response.isOK()) {
String key = JSON.parseObject(response.bodyString()).getString("key");
return ResponseEntity.ok(domain + "/" + key);
}
} catch (QiniuException e) {
e.printStackTrace();
}
return ResponseEntity.badRequest().build();
}
}
```
6. 程序运行后,在Vue中上传图片即可自动将图片上传到七牛云,并返回图片的访问URL。
阅读全文