1,注册账号并且得到认证.
2,得到AccessKey和SecretKey获取Token备用
public class QiNiuPhotoService {
public String uploadPhoto(MultipartFile mulFile){
String realmName = Global.getOption("system_trans", "realmName");
if(StringUtils2.isBlank(realmName)){
throw new ValidationException("请配置图片域名");
}
File file = multipartToFile(mulFile);
//构造一个带指定Zone对象的配置类
Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
String localFilePath = file.getAbsolutePath();
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = null;
String upToken = getToKen();
try {
Response response = uploadManager.put(localFilePath, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
return realmName+File.separatorChar+putRet.key;
} catch (QiniuException ex) {
throw new ValidationException("文件上传失败");
// Response r = ex.response;
// System.err.println(r.toString());
} catch (Exception e){
throw new ValidationException("上传失败");
}
}
//获得toKen
public String getToKen(){
String accessKey = Global.getOption("system_trans", "AccessKey");
String secretKey = Global.getOption("system_trans", "SecretKey");
String bucket = Global.getOption("system_trans", "bucket");
if(StringUtils2.isBlank(accessKey) || StringUtils2.isBlank(secretKey) || StringUtils2.isBlank(bucket)){
throw new ValidationException("图片服务器地址配置有误,请检查");
}
Auth auth = Auth.create(accessKey, secretKey);
return auth.uploadToken(bucket);
}
/**
* 文件类型转换
*/
public File multipartToFile(MultipartFile multfile) {
CommonsMultipartFile cf = (CommonsMultipartFile)multfile;
//这个myfile是MultipartFile的
DiskFileItem fi = (DiskFileItem) cf.getFileItem();
File file = fi.getStoreLocation();
return file;
}
}
4,控制层
@RequestMapping(value = "qiNiuUpload")
public String qiNiuUpload(@RequestParam(value = "file", required = false) MultipartFile file, @RequestParam("name") String name, HttpServletRequest request, HttpServletResponse response, Model model){
if (file == null) {
return error("上传失败,请更换图片重试", response, model);
}
if(!file.getContentType().equals("image/png") && !file.getContentType().equals("image/jpeg") ){
return error("文件类型错误,请上传图片类型", response, model);
}
String fileName;
try{
fileName = qiNiuPhotoService.uploadPhoto(file);
}catch (ValidationException e){
return error("失败:"+e.getMessage(),response,model);
}catch (Exception e){
return error("上传失败",response,model);
}
model.addAttribute("path",fileName);
return success("成功!!", response, model);
}