Java实现简单上传图片到阿里云对象存储OSS
阿里云对象存储服务(Object Storage Service,简称 OSS)提供基于网络的数据存取服务。使用 OSS,可以通过网络随时存储和调用包括文本、图片、音频和视频等在内的各种非结构化数据文件。具有:1、易用性:简单易用,便于管理,深度集成数据处理服务;2、高可靠:多重冗余备份,服务设计可用性不低于99.99%;3、强安全:多层次安全防护,支持跨区域复制、异地容灾机制;4、低成本:总体TCO更低,生命周期管理进一步降低成本等特点。
在实现之前首先要购买阿里云对象存储OSS资源包并创建了Bucket。这里不详细介绍,只介绍实现的代码。
前端实现比较简单,可以采用插件,有layui,bootstrap-fileinput等优秀插件,这里使用layui。
前端代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>upload</title> <link rel="stylesheet" href="/static/build/layui.css" media="all"> </head> <body> <button type="button" class="layui-btn" id="test1"> <i class="layui-icon"></i>上传图片 </button> <script src="/static/build/layui.js"></script> <script> layui.use('upload', function(){ var upload = layui.upload; //执行实例 var uploadInst = upload.render({ elem: '#test1' //绑定元素 ,url: '/upload/' //上传接口 ,done: function(res){ //上传完毕回调,拿到路径(res.data)自己选择是在页面显示图片还是显示路径。 } ,error: function(){ //请求异常回调,自己根据需求来写错误提示以及下一步逻辑。 } }); }); </script> </body> </html>
后端接口:
@RequestMapping(value="/upload") @ResponseBody public JsonResult upload(MultipartFile file, HttpServletRequest request) { if (!file.isEmpty()) { try { SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); // 生成文件名称 String nameSuffix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")) .replaceAll(" ", "_").replaceAll(",", "") + format.format(DateUtil.date()) + new Random().nextInt(1000); //上传原始图片到阿里云 String uploadPath = ossFileUtil.uploadAliyun(file,nameSuffix); return new JsonResult(true, "上传成功",uploadPath); } catch (Exception e) { log.error("上传附件错误" + e.getMessage()); return new JsonResult(false, "系统未知错误"); } } else { return new JsonResult(false, "文件不能为空"); } }
JsonResult工具类:
public class JsonResult { private boolean flag; private String msg; private Object data; public JsonResult() { super(); } public JsonResult(boolean flag, String msg) { super(); this.flag = flag; this.msg = msg; } public JsonResult(boolean flag, String msg, Object data) { super(); this.flag = flag; this.msg = msg; this.data = data; } public boolean isFlag() { return flag; } public void setFlag(boolean flag) { this.flag = flag; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
上传图片到阿里云工具类:
<!-- 阿里云oss --> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency>
public class ossFileUtil { public String uploadAliyun(MultipartFile file,String fileName) throws IOException { // 1 获取上传需要的固定值 String endpoint ="oss-cn-shanghai.aliyuncs.com"; //你的站点 String accessKeyId = "<yourAccessKeyId>"; //你的acess_key_id String accessKeySecret = "<yourAccessKeySecret>"; //你的acess_key_secret String bucketName = "<yourBucketName>"; //你的bucket_name //外面获取文件输入流,最后方便关闭 InputStream in = file.getInputStream(); try { //2 创建OssClient对象 OSS ossClient =new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret); //3 获取文件信息,为了上传 // meta设置请求头 ObjectMetadata meta = new ObjectMetadata(); meta.setContentType("image/jpg"); //4 设置知道文件夹 ossClient.putObject(bucketName,fileName,in, meta); //5 关闭ossClient ossClient.shutdown(); //6 返回上传之后地址,拼接地址 String uploadUrl = "https://"+bucketName+"."+endpoint+"/"+fileName; return uploadUrl; }catch(Exception e) { e.printStackTrace(); return null; }finally { in.close(); } } }