利用element中的upload上传文件
后台上传文件接口
@ApiOperation(value = "上传")
@ResponseBody
@RequestMapping(value = "upload")
public Object upload(HttpServletRequest request) throws IOException {
MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;
Map
//上传文件失败,找不到文件直接退出,并返回错误信息
return buildFailure(getMessage(BssCode.F100200));
}
for (Map.Entry
MultipartFile file = entry.getValue();
//通过MultipartFile获取文件bytes以及文件名
String result = ossMgr.upload(file.getBytes(), file.getOriginalFilename());
return buildObj(result);
}
return buildFailure(getMessage(BssCode.F100200));
上传文件类:
@Override
public String upload(byte[] data, String originalFilename) {、
//设置上传的路径第一个参数为"sys-oss",第二个为上传池(七牛云、百度等)
OssConfigRo config = sysParamMgr.getTObjByCd(SysParamEn.oss.getCd(), OssConfigRo.class);
if (null == config) {
BssExpUtils.error("ossConfig 没有定义", log);
}
//获取文件的后缀名
String suffix = StringUtils.substringAfterLast(originalFilename, ".");
String replaceFilename = UuidUtils.getUuid() + "." + suffix;
String url = null;
if (LOCAL == config.getType()) {
url = new LocalUpload(config).upload(data, replaceFilename);
} else if (ALIYUN == config.getType()) {
url = new AliyunUpload(config).upload(data, replaceFilename);
} else if (QINIU == config.getType()) {
url = new QiniuUpload(config).upload(data, replaceFilename);
} else if (BAIDU == config.getType()) {
url = new BadiduUpload(config).upload(data, replaceFilename);
}
SysOssVo ossVo = new SysOssVo();
ossVo.setOrigNm(originalFilename);
ossVo.setStorNm(replaceFilename);
ossVo.setUrl(url);
ossVo.setTm(DateUtils.getCurrentTime());
ossVo.setSuffix(suffix);
ossVo.setSize(Long.valueOf(data.length));
try {
//将vo插入数据库记录
sysOssMgr.add(ossVo);
} catch (Exception e) {
log.warn(e.getMessage());
}
return url;
}
//七牛云操作
public String upload(byte[] data, String key) { if (null == auth) { init(); } try { //调用put方法上传,这里指定的key和上传策略中的key要一致 Response res = uploadManager.put(data, key, getUpToken(key)); //打印返回的信息 logger.info(res.bodyString()); String jsonStr = res.bodyString(); if (null != jsonStr) { Mapmap = JsonUtils.toMap(jsonStr); if (StringUtils.endsWith(domain, "/")) { return domain + map.get("key"); } return domain + "/" + map.get("key"); } } catch (QiniuException e) { Response r = e.response; // 请求失败时打印的异常的信息 logger.error(r.toString(), e); try { //响应的文本信息 logger.error(r.bodyString()); } catch (QiniuException e1) { //ignore } } return null; }
// 覆盖上传 public String getUpToken(String key) { //: ,表示只允许用户上传指定key的文件。在这种格式下文件默认允许“修改”,已存在同名资源则会被本次覆盖。 //如果希望只能上传指定key的文件,并且不允许修改,那么可以将下面的 insertOnly 属性值设为 1。 //第三个参数是token的过期时间 return auth.uploadToken(bucketName, key, 3600, new StringMap().put("insertOnly", 1)); //return auth.uploadToken(bucketname, key, 3600, null); }
//@PostConstruct public void init() { uploadManager = new UploadManager(new Configuration(Zone.zone0())); bucketManager = new BucketManager(auth,new Configuration(Zone.zone0())); auth = Auth.create(accessKey, secretKey); }