对接七牛云 web项目

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);

    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值