最近公司要保存用户的图片信息到阿里云,经过学习已经掌握了阿里云基本上传的开发步骤。过程还是比较顺利的,查看了很多博客,代码都不是很全,自己为了方便以后使用和回忆,所以我写篇博客记录一下当时的过程。因为api里面有详细的步骤,这里我不在详细描述,只写代码实现和大抵的步骤。
①上传阿里云maven需要配置的jar包
com.aliyun.oss aliyun-sdk-oss 2.2.3 org.apache.httpcomponents httpclient 4.4
注:org.apache.httpcomponents必须为4.4版本。
如果mven里面有4.3版本的httpclient 会造成版本冲突,配置之前先检查mven里面的配置。
如果有低版本,应先删除再配置高版本的httpclient。(我因为这个半天都在报错,切记)
②阅读api
地址:https://help.aliyun.com/document_detail/32010.html?spm=5176.doc32009.6.211.OeN2Uw
必须阅读几遍api,这样流程会大抵熟悉
③就是代码部分(上传接口)
package com.zhongqi.ChessMember.client.web.controller.xaingqi;import com.aliyun.oss.OSSClient;import com.aliyun.oss.model.ObjectMetadata;import com.aliyun.oss.model.PutObjectResult;import com.zhongqi.ChessMember.dto.UploadAddInfo;import com.zhongqi.ChessMember.entity.UploadFile;import com.zhongqi.ChessMember.service.xiangqi.UploadService;import com.zhongqi.common.controller.BaseController;import com.zhongqi.common.dto.JsonResponseResult;import com.zhongqi.common.util.BaseUtils;import org.apache.commons.codec.digest.DigestUtils;import org.apache.commons.io.IOUtils;import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.Date;/** * Created by jordan on 16/10/24. * @author 宁春笋 */@Controller@RequestMapping("/clientUpload")public class UploadController extends BaseController { Logger logger = Logger.getLogger(UploadController.class); @Autowired private UploadService uploadService; @RequestMapping("/upload") public void upload(@RequestParam(value = "file", required = false) MultipartFile uploadFile, HttpServletRequest request, HttpServletResponse response)throws Exception { JsonResponseResult result = new JsonResponseResult(); result.setCode(1); result.setMsg("导入文件失败"); if (!uploadFile.isEmpty()) { try { // 文件保存路径 String strPath = request.getSession().getServletContext().getRealPath("/uploadImgs"); System.out.println(" strPath"+ strPath); //获得上传文件的名字 String fileName = uploadFile.getOriginalFilename(); System.out.print("fileName"+fileName); //拿到文件的流进行加密 FileInputStream fis = new FileInputStream(strPath + "/"+fileName); String fileMD5= DigestUtils.md5Hex(IOUtils.toByteArray(fis)); UploadFile uploadFile1=uploadService.checkUploadFileInfo(fileMD5); if (uploadFile1==null){ File file = new File(strPath + "/"+fileName); // 转存文件到服务器 uploadFile.transferTo(file); /** * 从服务器读取存储阿里云 * 上传文件的名字:file.getName() * * 当前时间:getCurrentDate() * * 文件(bucketName里面创建的)Constant.filePath * */ String key =Constant.filePath+ "/" +getCurrentDate()+"/"+fileName; System.out.println("key"+key); String filePath =strPath+ "/" +fileName; // 存储阿里云 putObject(Constant.bucketName, key,filePath); UploadAddInfo uploadAddInfo =new UploadAddInfo(); uploadAddInfo.setFileMD5(fileMD5); uploadAddInfo.setFilePath(key); uploadAddInfo.setUploadDate(new Date()); Integer uploadId= uploadService.addUploadinfo(uploadAddInfo); if (uploadId!=null){ result.setCode(0); result.setMsg("导入成功"); result.setResponse(uploadAddInfo); } } } catch (FileNotFoundException f) { logger.error(f); throw f; } } response(BaseUtils.toJsonFromObject(result), response,logger); } // 存储阿里云 private void putObject(String bucketName, String key, String filePath) throws FileNotFoundException { // 初始化OSSClient OSSClient client = DefaultOSSClient.getDefaultOSSClient(); // 获取指定文件的输入流 File file = new File(filePath); InputStream content = new FileInputStream(file); // 创建上传Object的Metadata ObjectMetadata meta = new ObjectMetadata(); // 必须设置ContentLength meta.setContentLength(file.length()); Date expire = new Date(new Date().getTime() + 30 * 1000); meta.setExpirationTime(expire); // 上传Object. PutObjectResult result = client.putObject(Constant.bucketName, key, content, meta); // 打印ETag System.out.println("etag--------------->" + result.getETag()); } //时间处理 private static String getCurrentDate(){ Date date =new Date(); SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmss"); String timeDate =simpleDateFormat.format(date); return timeDate; }}
④用到的配置工具类
DefaultOSSClient类
package com.zhongqi.ChessMember.client.web.controller.xaingqi;import com.aliyun.oss.OSSClient;import com.zhongqi.ChessMember.client.config.DefaultClientConfiguration;/** * Created by jordan on 16/10/21. * @author 宁春笋 */public class DefaultOSSClient { /* * Constructs a client instance with your account for accessing OSS */ private static OSSClient client = new OSSClient(Constant.endpoint, Constant.accessKeyId, Constant.accessKeySecret, DefaultClientConfiguration.getDefalutClientConfig()); private DefaultOSSClient() { } public static OSSClient getDefaultOSSClient(){ if(client == null){ client = new OSSClient(Constant.endpoint,Constant.accessKeyId, Constant.accessKeySecret,DefaultClientConfiguration.getDefalutClientConfig()); } return client; } public static void shutdownOSSClient(){ client.shutdown(); client = null; }}
Constant类
Constant类
package com.zhongqi.ChessMember.client.web.controller.xaingqi;/** * Created by jordan on 16/10/21. * @author 宁春笋 */public class Constant { public static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com"; public static String accessKeyId = "你的accessKeyId"; public static String accessKeySecret = "你的accessKeySecret"; public static String bucketName = "自己创建的bucket"; public static String filePath="自己创建的上传位置";}
默认配置可以查询api自己定义
package com.zhongqi.ChessMember.client.config;import com.aliyun.oss.ClientConfiguration;/** * Created by jordan on 16/10/21. * 宁春笋 */public class DefaultClientConfiguration { // 创建ClientConfiguration实例 private static final ClientConfiguration conf = new ClientConfiguration(); private DefaultClientConfiguration() { // 设置OSSClient使用的最大连接数,默认1024 conf.setMaxConnections(100); // 设置请求超时时间,默认50秒 conf.setConnectionTimeout(5000); // 设置失败请求重试次数,默认3次 conf.setMaxErrorRetry(3); //Socket层传输数据的超时时间(单位:毫秒)。默认为50000毫秒 conf.setSocketTimeout(2000); } public static ClientConfiguration getDefalutClientConfig(){ return conf; }}
⑤service实现
package com.zhongqi.ChessMember.service.xiangqi.impl;import com.zhongqi.ChessMember.dao.xiangqi.UploadDao;import com.zhongqi.ChessMember.dto.UploadAddInfo;import com.zhongqi.ChessMember.entity.UploadFile;import com.zhongqi.ChessMember.service.xiangqi.UploadService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;/** * Created by jordan on 16/10/24. */@Service("uploadService")public class UploadServiceImpl implements UploadService{ @Autowired private UploadDao uploadDao; //存储上传信息 @Override @Transactional public Integer addUploadinfo(UploadAddInfo uploadAddInfo) { return uploadDao.addUploadinfo(uploadAddInfo); } @Override public UploadFile checkUploadFileInfo(String fileMD5) { return uploadDao.checkUploadFileInfo(fileMD5); }}
⑥dao实现
package com.zhongqi.ChessMember.dao.xiangqi.impl;import com.zhongqi.ChessMember.dao.xiangqi.UploadDao;import com.zhongqi.ChessMember.dto.UploadAddInfo;import com.zhongqi.ChessMember.entity.UploadFile;import com.zhongqi.common.dao.impl.BaseDaoImpl;import org.apache.log4j.Logger;import org.springframework.stereotype.Repository;/** * Created by jordan on 16/10/24. * @author 宁春笋 */@Repository("uploadDao")public class UploadImpl extends BaseDaoImpl implements UploadDao { Logger logger = Logger.getLogger(UploadImpl.class); //存储上传信息 @Override public Integer addUploadinfo(UploadAddInfo uploadAddInfo) { Integer result =0; UploadFile uploadFile =new UploadFile(); uploadFile.setFileMD5(uploadAddInfo.getFileMD5()); uploadFile.setFilePath(uploadAddInfo.getFilePath()); uploadFile.setUploadDate(uploadAddInfo.getUploadDate()); try { save(uploadFile); result=uploadFile.getId(); }catch (Exception e){ logger.error(e); } return result; } //效验图片MD5值 @Override public UploadFile checkUploadFileInfo(String fileMD5) { String hql = "from UploadFile where fileMD5=?"; Object[] params ={fileMD5}; UploadFile uploadFile =(UploadFile)get(hql,params); return uploadFile; }}
⑦实体和工具
package com.zhongqi.ChessMember.entity;import javax.persistence.*;import java.util.Date;/** * Created by jordan on 16/10/24. * @author 宁春笋 */@Entity@Table(name="uploadFile")public class UploadFile { //主键 private Integer id; // 文件MD5值 private String fileMD5; // 存储路径 private String filePath; //上传日期 private Date uploadDate; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id", unique = true, nullable = false) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="fileMD5",nullable=true) public String getFileMD5() { return fileMD5; } public void setFileMD5(String fileMD5) { this.fileMD5 = fileMD5; } @Column(name="filePath",nullable=true) public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } @Column(name="uploadDate",nullable=true) public Date getUploadDate() { return uploadDate; } public void setUploadDate(Date uploadDate) { this.uploadDate = uploadDate; }}
UploadAddInfo类
package com.zhongqi.ChessMember.dto;import java.util.Date;/** * Created by jordan on 16/10/24. */public class UploadAddInfo { //主键 private Integer id; // 文件MD5值 private String fileMD5; // 存储路径 private String filePath; //上传日期 private Date uploadDate; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getFileMD5() { return fileMD5; } public void setFileMD5(String fileMD5) { this.fileMD5 = fileMD5; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public Date getUploadDate() { return uploadDate; } public void setUploadDate(Date uploadDate) { this.uploadDate = uploadDate; }}
以上是上传涉及的所有代码,上传是一个比较常用的模块,完全可以单拉一个站点出来。以便以后服用,阿里云存储安全性也比较高,避免用户数据的丢失。作为一个菜鸟,希望大家多多支持。2016/11/1