原创

七牛云多文件上传简单实例

话不多说上传的太多了,就直接上代码吧,如下:

Controller中:

/**
* 上传图片文件七牛云
* @param files
* @return
*/
@PostMapping(value = "/uploadImg")
@ApiOperation(value = "上传图片文件七牛云多文件", notes = "多文件上传")
public R uploadImg(@RequestParam("files") MultipartFile[] files) {

// 返回类型可以自己定义
List<String> resultList = null;
// 验证非空
if (StringUtils.isBlank(files[0].getOriginalFilename())) {
R.error("验证非空");
} else {
Map<String,List<String>> map = new HashMap<>();

map = fileService.uploadImgs(files);

resultList = map.get("result");
logger.info("图片上传返回结果:"+resultList);

if ("error".equals(resultList.get(0))) {
R.error("上传错误");
} else {
R.error("");
}
}
return R.ok().put("data", resultList);
}

Service接口:

/**
* @author 创建人:< zheng>
* @project 项目:<>
* @date 创建时间:< 2019/10/25>
* @comments: 说明:< //TODO >
*/
public interface FileService {
/**
* 多文件上传
* @param file
* @return
*/
Map<String, List<String>> uploadImgs(MultipartFile[] file);
}

ServiceImpl实现类:

@Service("fileService")
public class FileServiceImpl implements FileService{
private static final Logger logger = Logger.getLogger(FileServiceImpl.class);


/**
* 七牛云上传图片
* @param file
* @return
*/
@Override
public Map<String, List<String>> uploadImgs(MultipartFile[] file) {

Map<String, List<String>> resultMap = new HashMap<>();
List<String> list = new LinkedList<>();
String result = null;

for (int i = 0; i < file.length; i++) {
String fileName = file[i].getOriginalFilename();
String substring = "";
int indexOf = fileName.indexOf(".");
if(indexOf!=-1){
substring = fileName.substring(indexOf, fileName.length());

}
// 创建一个临时目录文件
String tempFiles = "temp/"+fileName;
File dest = new File(tempFiles);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}

BufferedOutputStream out = null;
QiniuUtil qn = new QiniuUtil();

try {
out = new BufferedOutputStream(new FileOutputStream(dest));
out.write(file[i].getBytes());
result = qn.uoloapQiniu(dest,substring);

if (StringUtils.isNotBlank(result)) {
list.add(result);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.getMessage();
} finally{
try {
if (null != out) {
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}

if (dest.getParentFile().exists()) {
dest.delete();
}
}
}
logger.info("imagesList == " + list);
if (list.isEmpty()) {
list.add("error");
}
resultMap.put("result",list);
return resultMap;
}
}

QiniuUtil工具类:

/**
* @author 创建人:< zheng>
* @project 项目:<>
* @date 创建时间:< 2019/10/25>
* @comments: 说明:< //七牛云图片配置 >
*/
public class QiniuUtil {


private static final Logger logger = Logger.getLogger(QiniuUtil.class);



//设置好账号的ACCESS_KEY和SECRET_KEY
final String ACCESS_KEY = "";//配置自己的accessKEY
final String SECRET_KEY = "";//配置自己的secretKey
//要上传的空间
final String BUCKET_NAME = "";//自己的空间
/**
* 七牛云上传图片
* @param localFilePath
* @return
*/
public String uoloapQiniu (File localFilePath,String fileName){
// fileName.
//构造一个带指定Zone对象的配置类
Configuration cfg;
cfg = new Configuration(Zone.zone1());//zone是存储区域,查看你的是那个区域 :z0 华东 z1 华北 z2 华南 na0 北美 as0 东南亚
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = ACCESS_KEY;
String secretKey = SECRET_KEY;
String bucket = BUCKET_NAME;
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = "images/"+System.currentTimeMillis()+fileName;
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);

String result = null;

try {
Response response = uploadManager.put(localFilePath, key, upToken);
//解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);

logger.info("{七牛图片上传key: "+ putRet.key+",七牛图片上传hash: "+ putRet.hash+"}");

result = "{外链域名(如:image.domain.com)}"+putRet.key;
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
//ignore
}
result = null;
}
return result;
}
}

以上是整个后台的简单流程,如有不对,请多多指教。


正文到此结束