public class QiniuUtils {
public static String accessKey = "zti_zX2hOWIpW8U_JGBAYBEPQyEvxaSWNYjJ9fby";
public static String secretKey = "3W465cTHVyXyaBvVzY5gpNNkYtFISMRsA8SCKg";
public static String bucket = "healthbyjava";
public static void upload2Qiniu(byte[] bytes, String fileName){
//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Region.region0());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = fileName;
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(bytes, key, upToken);
//解析上传成功的结果
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) {
//ignore
}
}
}
}
public Result upload(@RequestParam("imgFile") MultipartFile imgFile, HttpSession session) {
//构造一个带指定 Region 对象的配置类
Configuration cfg = new Configuration(Region.region0());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = "zti_zX2hOWIpW8U_JGBAYBEPQyEvxaSWNYjJ9fby";
String secretKey = "3W465cTHVyXyaBvVzY5gpNNkYtFISMRsA8SCKg-Z";
String bucket = "healthbyjava";
String originalFilename = imgFile.getOriginalFilename();//原始文件名 3bd90d2c-4e82-42a1-a401-882c88b06a1a2.jpg
int index = originalFilename.lastIndexOf(".");
String extention = originalFilename.substring(index);//.jpg
String fileName = UUID.randomUUID().toString() + extention;// FuM1Sa5TtL_ekLsdkYWcf5pyjKGu.jpg
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
try {
Response response = uploadManager.put(imgFile.getBytes(), fileName, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
System.out.println(putRet.key);
System.out.println(putRet.hash);
return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,putRet.key);
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
} catch (IOException e) {
e.printStackTrace();
}
return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS);
}
我用七牛云的文件上传
第一个我封装了代码,调用结果报错{"error":"bad token"},
第二个段代码我没有封装,可以上传图片,求解,出错在哪?
建议楼主立即到密钥管理位置,更换新的密钥对,该密钥已经不安全
账号涉及到了 ak sk 的问题,直接去 https://support.qiniu.com/hc/ 提交工单咨询