-
pom引入
<!-- 阿里云OSS对象存储控制台--> <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency>
2.OssUtils工具类
package com.example.jl.utils; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectResult; import com.itextpdf.text.log.Logger; import com.itextpdf.text.log.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.Date; import java.util.List; import java.util.UUID; /** * @Author HOUJL * @Date 2022/4/15 * @Description: */ @Component public class OssUtil { private static final Logger LOGGER = 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 = "aliyunOssFile/"; /** * 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(List<MultipartFile> fileList) { String fileUrl = ""; String str = ""; String photoUrl = ""; for (int i = 0; i < fileList.size(); i++) { fileUrl = uploadImg2Oss(fileList.get(i)); str = getFileUrl(fileUrl); if (i == 0) { photoUrl = str; } else { photoUrl += "," + str; } } return photoUrl.trim(); } /** * 3、通过文件名获取文件完整件路径 * * @param fileUrl * @return 完整URL路径 */ public String getFileUrl(String fileUrl) { if (fileUrl != null && fileUrl.length() > 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(System.currentTimeMillis() + 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) { LOGGER.error(e.getMessage(), e); } finally { try { if (instream != null) { instream.close(); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } 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"; } }
3.OssController测试
package com.example.jl.controller; import com.example.jl.utils.OssUtil; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.util.HashMap; import java.util.Map; /** * @Author HOUJL * @Date 2022/4/15 * @Description:阿里云oss图片上传 */ @RestController @RequestMapping("/oss") public class OssController { private final OssUtil ossUtil; public OssController(OssUtil ossUtil) { this.ossUtil = ossUtil; } @PostMapping("/uploadfile") public Object fileUpload(@RequestParam("file") MultipartFile file) { try { String url = ossUtil.uploadFile(file); Map<String, Object> returnbody = new HashMap<>(); Map<String, Object> returnMap = new HashMap<>(); returnMap.put("url", url); returnbody.put("data",returnMap); returnbody.put("code","200"); returnbody.put("message","上传成功"); return returnbody; } catch (Exception e) { Map<String, Object> returnbody = new HashMap<>(); returnbody.put("data",null); returnbody.put("code","400"); returnbody.put("message","上传失败"); return returnbody; } } }
4.application.yml
aliyun: oss: #yourEndpoint填写Bucket所在地域对应的Endpoint,可在创建好的Bucket概况页查看。 endpoint: oss-cn-chengdu.aliyuncs.com # 以成都为例,Endpoint填写为https://oss-cn-chengdu.aliyuncs.com #阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户 accessKeyId: # 阿里云账号AccessKey里所对应的AccessKey ID accessKeySecret: # 阿里云账号AccessKey里所对应的AccessKey Secret bucketName: # OSS对象存储空间名
阿里云oss图片上传
于 2022-04-22 17:45:36 首次发布