对于系统中的一些图片等资源,我们选择了国内领先的云服务提供厂商七牛云。由于流量不是很大,所以免费使用了七牛云对象存储服务。
![](https://i-blog.csdnimg.cn/blog_migrate/7074011f37665cc925828088a91bea0b.png)
七牛云对象存储服务与后端java代码整合
// 上传图片到七牛云
@RequestMapping(value = "/uploadPicture",method = RequestMethod.POST)
public ServerResponse uploadPicture(MultipartFile file){
try {
byte[] bytes = file.getBytes();
String imageName = UUID.randomUUID().toString();
String url = "";
try {
//使用base64方式上传到七牛云
url = QiniuCloudUtil.put64image(bytes, imageName);
} catch (Exception e) {
e.printStackTrace();
}
return ServerResponse.createBySuccess("文件上传成功",url);
} catch (IOException e) {
return ServerResponse.createByError("文件上传发生异常!");
}
}
// 设置需要操作的账号的AK和SK
private static final String ACCESS_KEY = "fJDkwchyRj26iOFwwRB6516Kc55y-ba_ge1WNiqb";
private static final String SECRET_KEY = "HqYIENRfB0bbOevLb8KDrvm-tbWoL_zCPQIxi24I";
// 要上传的空间
private static final String bucketname = "onlineexam-images";
// 密钥
private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
//base64方式上传
public static String put64image(byte[] data, String key){
//图片的外链地址
StringBuffer imgUrl = new StringBuffer("http://qwkvazbym.hn-bkt.clouddn.com/");
//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone2());
UploadManager uploadManager = new UploadManager(cfg);
//生成上传凭证,然后准备上传
String upToken = auth.uploadToken(bucketname);
//默认不指定key的情况下,以文件内容的hash值作为文件名
// String key = null;
try {
//上传文件
Response response = uploadManager.put(data,key,upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
imgUrl.append(putRet.key);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
}
}
return imgUrl.toString();
}
//删除图片
public static void deleteImage(String imgSrc) {
try {
Configuration cfg = new Configuration(Zone.zone0());
BucketManager bucketManager = new BucketManager(auth, cfg);
String key = imgSrc.substring(26);
bucketManager.delete(bucketname, key);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
}
}