详解SpringBoot上传图片到阿里云的OSS对象存储中

详解SpringBoot上传图片到阿里云的OSS对象存储中

2023年7月3日发(作者:)

详解SpringBoot上传图⽚到阿⾥云的OSS对象存储中启动idea创建⼀个SpringBoot项⽬将上⾯的步骤完成之后,点击下⼀步创建项⽬创建完成之后修改⽂件,添加阿⾥云oss依赖 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 ;import ent;import Metadata;import ectResult;import ;import Factory;import ;import ent;import artFile;import ption;import tream;import ;import .*;/** * 阿⾥云OSS服务器⼯具类 */@Componentpublic class OssUtil { //---------变量---------- protected static final Logger log = ger(); @Value("${nt}") private String endpoint; @Value("${KeyId}") private String accessKeyId; @Value("${KeySecret}") private String accessKeySecret; @Value("${Name}") 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 (); } /** * 1、单个⽂件上传(指定⽂件名(带后缀)) * @param file * @return 返回完整URL地址 */ public String uploadFile(MultipartFile file,String fileName) { try { InputStream inputStream = utStream(); File2OSS(inputStream, fileName); return fileName; } catch (Exception e) { return "上传失败"; } } /** * 2、多⽂件上传 * @param fileList * @return 返回完整URL,逗号分隔 */ public String uploadFile(List fileList) { String fileUrl = ""; String str = ""; String photoUrl = ""; for(int i = 0;i< ();i++){ fileUrl = uploadImg2Oss((i)); str = getFileUrl(fileUrl); if(i == 0){ photoUrl = str; }else { photoUrl += "," + str; } } return (); } /** * 3、通过⽂件名获取⽂完整件路径 * @param fileUrl * @return 完整URL路径 */ public String getFileUrl(String fileUrl) { if (fileUrl !=null && ()>0) { String[] split = ("/"); String url = (r + split[ - 1]); return url; } return null; } //获取去掉参数的完整路径 private String getShortUrl(String url) { String[] imgUrls = ("?"); 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 = tePresignedUrl(bucketName, key, expiration); if (url != null) { return getShortUrl(ng()); } return null; } // 上传⽂件 private String uploadImg2Oss(MultipartFile file) { //1、限制最⼤⽂件为20M if (e() > 1024 * 1024 *20) { return "图⽚太⼤"; } String fileName = ginalFilename(); String suffix = ing(dexOf(".")).toLowerCase(); //⽂件后缀 String uuid = UUID().toString(); String name = uuid + suffix; try { InputStream inputStream = utStream(); File2OSS(inputStream, name); return name; } catch (Exception e) { return "上传失败"; } } // 上传⽂件(指定⽂件名) private String uploadFile2OSS(InputStream instream, String fileName) { String ret = ""; try { //创建上传Object的Metadata ObjectMetadata objectMetadata = new ObjectMetadata(); tentLength(ble()); heControl("no-cache"); der("Pragma", "no-cache"); tentType(getcontentType(ing(dexOf(".")))); tentDisposition("inline;filename=" + fileName); //上传⽂件 OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); PutObjectResult putResult = ect(bucketName, filedir + fileName, instream, objectMetadata); ret = g(); } catch (IOException e) { (sage(), e); } finally { try { if (instream != null) { (); } } catch (IOException e) { tackTrace(); } } return ret; } private static String getcontentType(String FilenameExtension) { if (IgnoreCase(".bmp")) { return "image/bmp"; } if (IgnoreCase(".gif")) { return "image/gif"; } if (IgnoreCase(".jpeg") || IgnoreCase(".jpg") || IgnoreCase(".png")) { return "image/jpeg"; } if (IgnoreCase(".html")) { return "text/html"; } if (IgnoreCase(".txt")) { return "text/plain"; } if (IgnoreCase(".vsd")) { return "application/"; } if (IgnoreCase(".pptx") || IgnoreCase(".ppt")) { return "application/-powerpoint"; } if (IgnoreCase(".docx") || IgnoreCase(".doc")) { return "application/msword"; } if (IgnoreCase(".xml")) { return "text/xml"; } //PDF if (IgnoreCase(".pdf")) { return "application/pdf"; } return "image/jpeg"; }}OssController类package ller;import l;import red;import tion.*;import artFile;import p;import ;@RestController@RequestMapping("/oss")public class OssController { @Autowired OssUtil ossUtil; //注⼊OssUtil @PostMapping("/uploadfile") public Object fileUpload(@RequestParam("file") MultipartFile file) { try { String url = File(file); //调⽤OSS⼯具类 Map returnbody = new HashMap<>(); Map returnMap = new HashMap<>(); ("url", url); ("data",returnMap); ("code","200"); ("message","上传成功"); return returnbody; } catch (Exception e) { Map returnbody = new HashMap<>(); ("data",null); ("code","400"); ("message","上传失败"); return returnbody; } }}使⽤postman进⾏请求这样就可以将⽂件上传到阿⾥云OSS啦另外如果对这个项⽬不懂的,可以再底部留⾔哦,看见回复。要源码的⼩伙伴我将源码放在码云,⾃取哦!总结到此这篇关于详解SpringBoot上传图⽚到阿⾥云的OSS对象存储中的⽂章就介绍到这了,更多相关SpringBoot上传阿⾥云的OSS内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1688383886a129903.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信