import com.alibaba.fastjson.JSONObject;
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.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.UUID;
/**
* 七牛云上传
*/
@Slf4j
@Component
public class QiNiuUtil {
@Value("${qiniu.accessKey}")
private String accessKey ;
@Value("${qiniu.secretKey}")
private String secretKey ;
@Value("${qiniu.bucketname}")
private String bucketName ;
@Value("${qiniu.domain}")
private String domain ;
// 设置好账号的ACCESS_KEY和SECRET_KEY
private static String ACCESS_KEY ;
private static String SECRET_KEY;
// 要上传的空间
private static String bucket_Name ;
//域名
private static String qiniuDoamin ;
@PostConstruct
public void init() {
QiNiuUtil.ACCESS_KEY = accessKey;
QiNiuUtil.SECRET_KEY = secretKey;
QiNiuUtil.bucket_Name = bucketName;
QiNiuUtil.qiniuDoamin = domain;
}
public static String saveImage(MultipartFile file) {
try {
// 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
//TODO 这个地区到时候要切回来,域名没好前用海外的地区
Configuration cfg = new Configuration(Zone.zoneNa0());
UploadManager uploadManager = new UploadManager(cfg);
int dotPos = file.getOriginalFilename().lastIndexOf(".");
if (dotPos < 0) {
return null;
}
String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
log.info("文件名称{}",fileName);
// 调用put方法上传
//获取token
String token = Auth.create(ACCESS_KEY, SECRET_KEY).uploadToken(bucket_Name);
Response res = uploadManager.put(file.getBytes(), fileName, token);
log.info("------七牛开始返回上传结果--------");
log.info("七牛返回上传结果[{}]",res);
// 打印返回的信息
if (res.isOK() && res.isJson()) {
// 返回这张存储照片的地址
return qiniuDoamin+JSONObject.parseObject(res.bodyString()).getString("key");
} else {
log.error("七牛异常:" + res.bodyString());
return null;
}
} catch (QiniuException e) {
// 请求失败时打印的异常的信息
log.error("七牛异常:" + e.getMessage());
return null;
} catch (Exception e) {
log.error("七牛异常:" + e.getMessage());
e.printStackTrace();
return null;
}
}
}
七牛云图片上传 java工具类
最新推荐文章于 2024-07-05 17:47:06 发布