启动idea创建一个SpringBoot项目
将上面的步骤完成之后,点击下一步创建项目
创建完成之后修改pom.xml文件,添加阿里云oss依赖
org.springframework.boot spring-boot-devtools runtime true
修改配置文件,将配置文件后缀名修改为yml类型的配置文件,并对阿里云oss进行参数的配置
server: port: 8088 # 阿里云存储参数配置 aliyun: oss: endpoint: accessKeyId: accessKeySecret: bucketName:
上面的参数我们首先进入阿里云官网,登录并进入自己的控制台
创建一个,方框中就是yml配置文件中的bucketName
点击进入就可以看见外网访问地址,将这个地址填写到yml配置文件中的endpoint
点击头像,选择AccessKey管理
选择继续使用AccessKey
创建一个AccessKey
创建成功,yml配置文件中的accessKeyId,accessKeySecret,对应填入相应位置
创建一个util(里面放oss工具类)文件夹,里面创建一个OssUtil的类。再创建一个Controller文件夹,里面创建一个OssController的文件
OssUtil类
package com.example.ossdemo.util; 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.web.multipart.MultipartFile; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.*; /** * 阿里云OSS服务器工具类 */ @Component public class OssUtil { //---------变量---------- protected static final Logger log = LoggerFactory.getLogger(OssUtil.class); @Value("${aliyun.oss.endpoint}") private String endpoint; @Value("${aliyun.oss.accessKeyId}") private String accessKeyId; @Value("${aliyun.oss.accessKeySecret}") private String accessKeySecret; @Value("${aliyun.oss.bucketName}") private String bucketName; //文件存储目录 private String filedir = "my_file/"; /** * 1、单个文件上传 * @param file * @return 返回完整URL地址 */ public String uploadFile(MultipartFile file) { String fileUrl = uploadImg2Oss(file); String str = getFileUrl(fileUrl); return str.trim(); } /** * 1、单个文件上传(指定文件名(带后缀)) * @param file * @return 返回完整URL地址 */ public String uploadFile(MultipartFile file,String fileName) { try { InputStream inputStream = file.getInputStream(); this.uploadFile2OSS(inputStream, fileName); return fileName; } catch (Exception e) { return "上传失败"; } } /** * 2、多文件上传 * @param fileList * @return 返回完整URL,逗号分隔 */ public String uploadFile(ListfileList) { String fileUrl = ""; String str = ""; String photoUrl = ""; for(int i = 0;i 0) { String[] split = fileUrl.split("/"); String url = this.getUrl(this.filedir + split[split.length - 1]); return url; } return null; } //获取去掉参数的完整路径 private String getShortUrl(String url) { String[] imgUrls = url.split("\\?"); return imgUrls[0].trim(); } // 获得url链接 private String getUrl(String key) { // 设置URL过期时间为20年 3600l* 1000*24*365*20 Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 20); // 生成URL OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); URL url = ossClient.generatePresignedUrl(bucketName, key, expiration); if (url != null) { return getShortUrl(url.toString()); } return null; } // 上传文件 private String uploadImg2Oss(MultipartFile file) { //1、限制最大文件为20M if (file.getSize() > 1024 * 1024 *20) { return "图片太大"; } String fileName = file.getOriginalFilename(); String suffix = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); //文件后缀 String uuid = UUID.randomUUID().toString(); String name = uuid + suffix; try { InputStream inputStream = file.getInputStream(); this.uploadFile2OSS(inputStream, name); return name; } catch (Exception e) { 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; } private 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"; } //PDF if (FilenameExtension.equalsIgnoreCase(".pdf")) { return "application/pdf"; } return "image/jpeg"; } }
OssController类
package com.example.ossdemo.controller; import com.example.ossdemo.util.OssUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/oss") public class OssController { @Autowired OssUtil ossUtil; //注入OssUtil @PostMapping("/uploadfile") public Object fileUpload(@RequestParam("file") MultipartFile file) { try { String url = ossUtil.uploadFile(file); //调用OSS工具类 Mapreturnbody = new HashMap<>(); Map returnMap = new HashMap<>(); returnMap.put("url", url); returnbody.put("data",returnMap); returnbody.put("code","200"); returnbody.put("message","上传成功"); return returnbody; } catch (Exception e) { Map returnbody = new HashMap<>(); returnbody.put("data",null); returnbody.put("code","400"); returnbody.put("message","上传失败"); return returnbody; } } }
使用postman进行请求
这样就可以将文件上传到阿里云OSS啦
另外如果对这个项目不懂的,可以再底部留言哦,看见回复。要源码的小伙伴我将源码放在码云,自取哦!
项目码云地址
总结
到此这篇关于详解SpringBoot上传图片到阿里云的OSS对象存储中的文章就介绍到这了,更多相关SpringBoot上传阿里云的OSS内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!