SpringBoot集成阿里云OSS图片上传

时间:2021-05-20

简述

最近做的公司项目,图片比较多,不想给其存储到自己服务器上,就买了阿里云的OSS服务器来哦进行存储,其实集成第三方平台,一般没什么难度,当然,你要仔细看对方的API文档,这篇主要说一下个人集成OSS的过程

步骤

1、pom.xml中添加OSS的SDK

<!-- 图片上传 SDK 阿里云oss --><dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.8.3</version></dependency>

2、必备参数

在application.yml中配置参数

bucketName: "空间名称" accessKeyId: "你的accessKeyId" accessKeySecret: "你的accessKeySecret" #OSS对应的区域 endpoint: http://oss-cn-beijing.aliyuncs.com

这四个参数在你的阿里云控制台中都能找到

①bucketName

②③accessKeyId和accessKeySecret

配置文件格式如图:

3、创建OSS工具类

/** * OssUtil.java * com.prereadweb.utils * Copyright (c) 2019, 北京链天下科技有限公司版权所有. */package com.prereadweb.utils; import com.aliyun.oss.OSSClient;import com.aliyun.oss.model.ObjectMetadata;import com.aliyun.oss.model.PutObjectResult;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import org.springframework.util.StringUtils;import org.springframework.web.multipart.MultipartFile; import java.io.IOException;import java.io.InputStream;import java.net.URL;import java.util.Date;import java.util.List;import java.util.Random; /** * @Description: 阿里云OSS服务器工具类 * @author: Yangxf * @date: 2019/4/18 16:26 */@Componentpublic class OssUtil { protected static final Logger log = LoggerFactory.getLogger(OssUtil.class); @Value("${aliyun.endpoint}") private String endpoint; @Value("${aliyun.accessKeyId}") private String accessKeyId; @Value("${aliyun.accessKeySecret}") private String accessKeySecret; @Value("${aliyun.bucketName}") private String bucketName; //文件存储目录 private String filedir = "userImg/"; /** * * 上传图片 * @param file * @return */ public String uploadImg2Oss(MultipartFile file) { if (file.getSize() > 1024 * 1024 *20) { return "图片太大";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_TOO_MAX); } String originalFilename = file.getOriginalFilename(); String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase(); Random random = new Random(); String name = random.nextInt(10000) + System.currentTimeMillis() + substring; try { InputStream inputStream = file.getInputStream(); this.uploadFile2OSS(inputStream, name); return name;//RestResultGenerator.createSuccessResult(name); } catch (Exception e) { return "上传失败";//RestResultGenerator.createErrorResult(ResponseEnum.PHOTO_UPLOAD); } } /** * 上传图片获取fileUrl * @param instream * @param fileName * @return */ private String uploadFile2OSS(InputStream instream, String fileName) { String ret = ""; try { //创建上传Object的Metadata ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(instream.available()); objectMetadata.setCacheControl("no-cache"); objectMetadata.setHeader("Pragma", "no-cache"); objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf(".")))); objectMetadata.setContentDisposition("inline;filename=" + fileName); //上传文件 OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata); ret = putResult.getETag(); } catch (IOException e) { log.error(e.getMessage(), e); } finally { try { if (instream != null) { instream.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; } public static String getcontentType(String FilenameExtension) { if (FilenameExtension.equalsIgnoreCase(".bmp")) { return "image/bmp"; } if (FilenameExtension.equalsIgnoreCase(".gif")) { return "image/gif"; } if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg") || FilenameExtension.equalsIgnoreCase(".png")) { return "image/jpeg"; } if (FilenameExtension.equalsIgnoreCase(".html")) { return "text/html"; } if (FilenameExtension.equalsIgnoreCase(".txt")) { return "text/plain"; } if (FilenameExtension.equalsIgnoreCase(".vsd")) { return "application/vnd.visio"; } if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) { return "application/vnd.ms-powerpoint"; } if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) { return "application/msword"; } if (FilenameExtension.equalsIgnoreCase(".xml")) { return "text/xml"; } return "image/jpeg"; } /** * 获取图片路径 * @param fileUrl * @return */ public String getImgUrl(String fileUrl) { if (!StringUtils.isEmpty(fileUrl)) { String[] split = fileUrl.split("/"); String url = this.getUrl(this.filedir + split[split.length - 1]); return url; } return null; } /** * 获得url链接 * * @param key * @return */ public String getUrl(String key) { // 设置URL过期时间为10年 3600l* 1000*24*365*10 Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 10); // 生成URL OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); URL url = ossClient.generatePresignedUrl(bucketName, key, expiration); if (url != null) { return url.toString(); } return null; } /** * 多图片上传 * @param fileList * @return */ public String checkList(List<MultipartFile> fileList) { String fileUrl = ""; String str = ""; String photoUrl = ""; for(int i = 0;i< fileList.size();i++){ fileUrl = uploadImg2Oss(fileList.get(i)); str = getImgUrl(fileUrl); if(i == 0){ photoUrl = str; }else { photoUrl += "," + str; } } return photoUrl.trim(); } /** * 单个图片上传 * @param file * @return */ public String checkImage(MultipartFile file){ String fileUrl = uploadImg2Oss(file); String str = getImgUrl(fileUrl); return str.trim(); }}

4、controller层代码

/** * @Function: 用户图片上传 * @author: Yangxf * @Date: 2019/4/17 15:42 */ @PostMapping("/postfile") public Object fileUpload(@RequestParam(value = "userImg", required = false) MultipartFile file, @RequestParam(value = "userId", required = false) Long userId) { return personalService.fileUpload(file, userId); }

5、service层代码

/** * @Function: 用户头像上传 * @author: YangXueFeng * @Date: 2019/4/18 16:15 * @param: * @return: */ @Override public Map<String, Object> fileUpload(MultipartFile file, Long userId) { Map<String, Object> map = new HashMap<>(); if (Util.isEmpty(file)) { System.out.println("文件为空空"); return checkNull(map); } UserEntity user = userMapper.fetchUser(userId); if(Util.isEmpty(user)){ map.put("code", UserStatusEnum.USER_NOT_EXISTENCE.intKey()); map.put("msg", UserStatusEnum.USER_NOT_EXISTENCE.value()); return map; } String url = ossUtil.checkImage(file); String[] imgUrls = url.split("\\?"); updateUrl(userId, imgUrls[0]); Map<String, Object> returnMap = new HashMap<>(); returnMap.put("imageUrl", imgUrls[0]); map.put("data", returnMap); returnSuccess(map); return map; }

总结

对于第三对接来说,一般对方的API文档都会详细说明使用步骤的,所以,只要仔细看对方提供的API文档了,都没什么难的。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章