Springboot整合七牛云存储
springboot整合七牛云存储
·
先测试一下
- 引入依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.10.99]</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
- application.yaml
oss:
accessKey: 你自己的访问key
secretKey: 你自己的key
bucket: 你自己存储桶
- java代码
@SpringBootTest
@ConfigurationProperties(prefix = "oss")
public class TestqiNiu {
private String accessKey ;
private String secretKey;
private String bucket ;
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getBucket() {
return bucket;
}
public void setBucket(String bucket) {
this.bucket = bucket;
}
@Test
public void testOss() {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.autoRegion());
cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
// String accessKey = "ZT-HLW35rU8ddVQD3LFrrnZBcyk6_FW";
// String secretKey = "u4-qTOnnrZFyQihxBrmjRa6UyrYMHLroCx7XjNLdyt";
// String bucket = "srr";
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;
try {
// byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
// ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
FileInputStream inputStream = new FileInputStream("d:\\01.jpg");
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(inputStream,key,upToken,null, null);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
}
}
} catch (Exception ex) {
}
}
}
项目中整合
- 引入依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.7.0, 7.10.99]</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
</dependency>
- application
oss:
accessKey: 你自己的访问key
secretKey: 你自己的key
bucket: srr
- controller层
@Api("文件上传接口")
@RestController
@RequestMapping("/admin/vod/file")
@CrossOrigin
public class FileUploadController {
@Autowired
private FileService fileService;
@ApiOperation("文件上传")
@PostMapping("upload")
public R uploadFile(MultipartFile file){
String url = fileService.upload(file);
return R.ok(url).message("文件文件成功");
}
}
3.service层
接口
public interface FileService {
String upload(MultipartFile file);
}
实现类
@Service
@Data
@ConfigurationProperties(prefix = "oss")
public class FileServiceImpl implements FileService {
private String accessKey ;
private String secretKey;
private String bucket ;
/**
* 腾讯云: 文件上传
* @param file
* @return
*/
public String upload1(MultipartFile file) {
// 1 初始化用户身份信息(secretId, secretKey)。
String secretId = ConstantPropertiesUtil.ACCESS_KEY_ID;
String secretKey = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的地域, COS 地域的
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法
Region region = new Region(ConstantPropertiesUtil.END_POINT);
ClientConfig clientConfig = new ClientConfig(region);
// 这里建议设置使用 https 协议
// 从 5.6.54 版本开始,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);
// 3 生成 cos 客户端。
COSClient cosClient = new COSClient(cred, clientConfig);
//===================使用流上传====================
// 存储桶的命名格式为 BucketName-APPID,此处填写的存储桶名称必须为此格式
String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
// 对象键(Key)是对象在存储桶中的唯一标识。
String key = UUID.randomUUID().toString().replaceAll("-","")+
file.getOriginalFilename();
// 对上传文件分组,根据当前日期
String dateTime = new DateTime().toString("yyyy/MM/dd");
key = dateTime +"/"+key;
try {
// 这里创建一个 ByteArrayInputStream 来作为示例,实际中这里应该是您要上传的 InputStream 类型的流
InputStream is = file.getInputStream();
ObjectMetadata objectMetadata = new ObjectMetadata();
// 上传的流如果能够获取准确的流长度,则推荐一定填写 content-length
// 如果确实没办法获取到,则下面这行可以省略,但同时高级接口也没办法使用分块上传了
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, is, objectMetadata);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
// https://srr-1309466898.cos.ap-nanjing.myqcloud.com/2022/01/01.jpg
String url = "https://srr-1309466898.cos."+ConstantPropertiesUtil.END_POINT+".myqcloud.com/"+key;
return url;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 七牛云 文件上传
* @param file
* @return
*/
@Override
public String upload(MultipartFile file) {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(com.qiniu.storage.Region.autoRegion());
cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
// String accessKey = "ZT-HLW35U8dyDbLnZBcyk6_FW";
// String secretKey = "u4-qTOnnZFyQUyYMHLroCx7kXjNLdyt";
// String bucket = "srr";
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = UUID.randomUUID().toString().replaceAll("-","")+
file.getOriginalFilename();
// 对上传文件分组,根据当前日期
String dateTime = new DateTime().toString("yyyy/MM/dd");
key = dateTime +"/"+key;
try {
// byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
// ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
InputStream inputStream = file.getInputStream();
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(inputStream,key,upToken,null, null);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
String url = "https://qn.srrxixi.fun/"+key;
return url;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
}
} catch (Exception ex) {
//ignore
}
return null;
}
}
更多推荐
已为社区贡献1条内容
所有评论(0)