- 七牛云上传工具类,一个很小的demo了解一下七牛云上传的原理,记得引入maven配置。
七牛云JAVA文档地址
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/**
* Company :Co Ltd
* Created By : Administrator
* Created Date : 2018/11/18 22:47
* Description :
*/
public class PictureUtil {
public static String accessKey = "accessKey ";
public static String secretKey = "secretKey";
public static String bucket = "Bucket";
private static String QINIU_IMAGE_DOMAIN = "http://xxxxxx.bkt.clouddn.com";//改成他给你的免费的域名。
//普通本地上传
public static String upload(String localFilePath) {
// 构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone0());// 这里是华南,对应的2
UploadManager uploadManager = new UploadManager(cfg);
// 默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
DefaultPutRet putRet = null;
try {
Response response = uploadManager.put(localFilePath, key, upToken);
// 解析上传成功的结果
putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
// ignore
}
}
return QINIU_IMAGE_DOMAIN +"/"+ putRet.hash;
}
//文件流上传
public static String upload(MultipartFile file) throws IOException {
// 构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone2());
UploadManager uploadManager = new UploadManager(cfg);
// 默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;
DefaultPutRet putRet = null;
try {
byte[] uploadBytes = file.getBytes();
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
// ignore
}
}
} catch (UnsupportedEncodingException ex) {
// ignore
}
return QINIU_IMAGE_DOMAIN + putRet.hash;
}
public static void main(String[] args) {
String url = PictureUtil.upload("E:\\WorkSpace\\xunwu\\temp\\a.jpg");
System.out.println(url);
}
}
- 使用SpringBoot上传七牛云(引入maven配置)
首先在application.properties加入以下配置
#qiniu配置文件
qiniu.accessKey=你的accessKey
qiniu.secretKey=你的secretKey
qiniu.bucket=你的bucket
qiniu.cdn.prefix=你的CDN
抽象服务层
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import java.io.File;
import java.io.InputStream;
/**
* Company :Co Ltd
* Created By : Administrator
* Created Date : 2018/11/18 21:32
* Description : 七牛云文件上传抽象服务
*/
public interface IQiNiuService {
Response uploadFile(File file) throws QiniuException;
}
具体实现类
package com.imooc.base.service.house;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.InputStream;
/**
* Company : Co Ltd
* Created By : Administrator
* Created Date : 2018/11/18 21:35
* Description : 七牛云文件上传实现类
*/
@Service
public class QiNiuServiceImpl implements IQiNiuService,InitializingBean {
@Autowired
private UploadManager uploadManager;
@Autowired
private BucketManager bucketManager;
@Autowired
private Auth auth;
@Value("${qiniu.bucket}")
private String bucket;
private StringMap putPolicy;
@Override
public Response uploadFile(File file) throws QiniuException {
Response response = this.uploadManager.put(file,null,getUploadToken());
int retry = 0;
/**
* 重传次数
*/
while(response.needRetry() && retry < 3){
this.uploadManager.put(file,null,getUploadToken());
retry++;
}
return response;
}
/**
* 实例化StringMap
* @throws Exception
*/
@Override
public void afterPropertiesSet() throws Exception {
this.putPolicy = new StringMap();
putPolicy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"bucket\":\"$(bucket)\",\"width\":$(imageInfo.width),\"height\":$(imageInfo.height)}");
}
/**
* 获取上传凭证
* @return
*/
private String getUploadToken(){
return this.auth.uploadToken(bucket,null,3600,putPolicy);
}
}
package com.imooc.base.service.house;
import com.imooc.ApplicationTests;
import com.qiniu.http.Response;
import javafx.application.Application;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.File;
import static org.junit.Assert.*;
/**
* Company :Co Ltd
* Created By : Administrator
* Created Date : 2018/11/18 21:48
* Description :测试类
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class QiNiuServiceImplTest {
@Autowired
private IQiNiuService qiNiuService;
@Test
public void uploadFile() throws Exception {
String fileName = "E:\\WorkSpace\\xunwu\\temp\\a.jpg";
File file = new File(fileName);
Assert.assertTrue(file.exists());
Response response = qiNiuService.uploadFile(file);
Assert.assertTrue(response.isOK());
}
}