package com.service;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.zy.webserver.common.Constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.UUID;
@Service
public class FileService {
@Value("${qiniu.accessKey}")
private String accessKey;
@Value("${qiniu.secretKey}")
private String secretKey;
@Value("${qiniu.bucket}")
private String bucket;//桶
@Value("${qiniu.baseUrl}")
private String baseUrl;//域名
/**
* 上传到七牛云
* @param file
* @return
*/
public String uploadFile(MultipartFile file) {
//构造一个带指定 Region 对象的配置类
if (file.isEmpty()) {
return "文件为空";
}
Configuration cfg = new Configuration(Region.region2());
UploadManager uploadManager = new UploadManager(cfg);
try {
String originalFilename = file.getOriginalFilename();
byte[] bytes = file.getBytes();
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = originalFilename;
Response response = uploadManager.put(bytes, key, upToken);
if (response.statusCode != 200) {
return "上传失败";
}
return baseUrl+"/"+key;
} catch (Exception e) {
e.printStackTrace();
return "上传失败";
}
}
/**
* 获取下载七牛云文件路径
* @param baseUrl 域名+key
* @return
*/
public String downloadFile(String baseUrl) {
Auth auth = Auth.create(accessKey, secretKey);
String downloadUrl = auth.privateDownloadUrl(baseUrl);
return downloadUrl;
}
/**
* 删除七牛云文件
* @param baseUrl
* @return
*/
public Boolean deleteFile(String fileName) {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region0());
Auth auth = Auth.create(accessKey, secretKey);
BucketManager bucketManager = new BucketManager(auth, cfg);
try {
bucketManager.delete(bucket,fileName);
} catch (Exception ex) {
//如果遇到异常,说明删除失败
return false;
}
return true;
}
}
七牛云私有桶文件操作
最新推荐文章于 2024-06-03 15:17:28 发布