SpringBoot集成阿里云OSS图片上传
作者:Snow、杨 时间:2021-08-15 21:01:55
简述
最近做的公司项目,图片比较多,不想给其存储到自己服务器上,就买了阿里云的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
*/
@Component
public 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文档了,都没什么难的。
来源:https://blog.csdn.net/qq_37345604/article/details/90178786
标签:SpringBoot,阿里云,图片上传
0
投稿
猜你喜欢
Java ArrayList深入源码层分析
2021-10-18 04:12:31
Java Web实现简易图书管理系统
2023-12-17 21:48:34
老生常谈反射之Class类的使用(必看篇)
2022-07-20 16:32:30
如何利用Android仿微博正文链接交互效果
2022-03-22 03:41:41
internal修饰符探索kotlin可见性控制详解
2023-03-09 10:15:22
浅谈java中守护线程与用户线程
2023-11-26 20:46:41
springboot集成开发实现商场秒杀功能
2022-06-23 11:05:27
Java StringBuilder和StringBuffer源码分析
2023-04-03 00:10:58
C#将Json解析成DateTable的方法
2022-11-19 20:10:42
java开发之MD5加密算法的实现
2022-05-13 23:44:35
SQLite在C#中的安装与操作技巧
2023-04-19 08:31:12
Java计算器核心算法代码实现
2022-03-18 05:38:55
SpringBoot添加自定义拦截器的实现代码
2023-11-26 13:30:54
Spring Boot 定义系统启动任务的多种方式
2023-11-24 13:25:33
Android中的popupwindow进入和退出的动画效果
2022-05-24 19:46:15
在 Ubuntu Linux 上安装 Oracle Java 14的方法
2022-01-01 15:13:52
Android简单实现圆盘抽奖界面
2022-07-25 08:35:27
Java最全文件操作实例汇总
2023-11-14 13:00:17
Gradle的使用教程详解
2022-08-12 05:02:11
详解Android Webview加载网页时发送HTTP头信息
2023-11-16 02:32:34