为什么要使用七牛云
一直以来很多公司,都在自己的服务器来存储自己的照片,这样非常的耗费带宽,同时每一次服务器迁移都会出现图片找不到的情况,七牛云就刚好的帮我们解决了这个问题,我们只需要给图片的URL存储到我们的数据库中,就可以做到高效且快速的图片浏览,节约我们的服务器的带宽。
七牛云的控制台
1.首先我们要在七牛云上设置我们空间,设置秘钥,通过他们的JAR包,集成到项目就可以调用七牛云的端口啦。
代码基于springBoot 2.0的。Java8
先写一个上传的工具类
package com.keelon.job.util;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
//import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.UUID;
public class QiniuUtil {
//设置好账号的ACCESS_KEY和SECRET_KEY
final String ACCESS_KEY = "aObyrVTNwP0MP0kg0IyFrkB92q7cboWSZL4LggKn";
final String SECRET_KEY = "Ua3zlnAE-2Tu99IRIAoyfCw3J4O1u-IB9dpSCFQu";
//要上传的空间
final String BUCKET_NAME = "51job";
/**
* 七牛云上传图片
* @param localFilePath
* @return
*/
public String uoloapQiniu (File localFilePath,String fileName){
//构造一个带指定Zone对象的配置类
Configuration cfg;
cfg = new Configuration(Zone.zone2());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证,然后准备上传
String accessKey = ACCESS_KEY;
String secretKey = SECRET_KEY;
String bucket = BUCKET_NAME;
//如果是Windows情况下,格式是 D:\23912475_130759767000_2.jpg
// String localFilePath = "D:\\23912475_130759767000_2.jpg";
// String localFilePath = "/home/qiniu/test.png";
//默认不指定key的情况下,以文件内容的hash值作为文件名
String key = "images/"+fileName+"tId="+System.currentTimeMillis();
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 =
"http://pw9sd0p5d.bkt.clouddn.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;
}
}
第二步写一个文件上传的service
package com.keelon.job.Service.ServiceImpl;
import com.keelon.job.Service.FileService;
import com.keelon.job.util.QiniuUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.util.StringUtil;
//import tk.mybatis.mapper.util.StringUtil;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* @author 创建人:< Chenmq>
* @project 项目:<chuangyin-data>
* @date 创建时间:< 2017/9/2>
* @comments: 说明:< //文件上传 >
*/
@Service
public class FileServiceImpl implements FileService {
@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 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,fileName);
// StringUtil.isNotEmpty()
if (StringUtil.isNotEmpty(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);
System.out.println("imagesList == " + list);
if (list.isEmpty()) {
list.add("error");
}
resultMap.put("result",list);
return resultMap;
}
}
第三步我们编写我们的Controller
import com.keelon.job.VO.ResultVO;
import com.keelon.job.util.ResultVOUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.util.StringUtil;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/admin/webServer")
public class WebServerController {
@Resource
private FileService fileService;
@RequestMapping(value="/imgs", method = RequestMethod.POST)
public ResultVO uploadImg(@RequestParam("file") MultipartFile[] files) {
// 返回类型可以自己定义
ResultVO serviceResult = new ResultVO();
// 验证非空
if (StringUtil.isEmpty(files[0].getOriginalFilename())) {
serviceResult = ResultVOUtil.error(-1,"照片为空");
} else {
Map<String,List<String>> map = new HashMap<>();
map = fileService.uploadImgs(files);
List<String> resultList = map.get("result");
System.out.println("图片上传返回结果:"+resultList);
if ("error".equals(resultList.get(0))) {
serviceResult = ResultVOUtil.error(-2,"上传失败");
} else {
//上传成功。返回地址。
serviceResult = ResultVOUtil.success(resultList);
}
}
return serviceResult;
}
}
第四部:我们用postman测试一下刚才写的接口。服务器已经返回,证明我们测试以及OK了
下面我们进入七牛云的
后台看看,我们上传的图片
通过以上代码来看,我们照片的存储是不是很简单呢。既然七牛云可以上传我们照片。那么是不是做一个图片的分享或者照片的分享app呢。当然七牛云,存储容量非常大的时候,还是需要付费,但是价格还是能够接受的。