• IDEA阿里云OSS实现文件上传·解决苍穹外卖图片回显


    简单交代配置阿里云OSS的思路

    1. 首先去阿里云开通一个OSS服务,配置好一个自己的Bucket

    2. 在IDEA配置Bucket

    3. 拷贝官网的OSS工具类代码

    1. package com.sky.utils;
    2. import com.aliyun.oss.ClientException;
    3. import com.aliyun.oss.OSS;
    4. import com.aliyun.oss.OSSClientBuilder;
    5. import com.aliyun.oss.OSSException;
    6. import lombok.AllArgsConstructor;
    7. import lombok.Data;
    8. import lombok.extern.slf4j.Slf4j;
    9. import java.io.ByteArrayInputStream;
    10. @Data
    11. @AllArgsConstructor
    12. @Slf4j
    13. public class AliOssUtil {
    14. private String endpoint;
    15. private String accessKeyId;
    16. private String accessKeySecret;
    17. private String bucketName;
    18. /**
    19. * 文件上传
    20. *
    21. * @param bytes
    22. * @param objectName
    23. * @return
    24. */
    25. public String upload(byte[] bytes, String objectName) {
    26. // 创建OSSClient实例。
    27. OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    28. try {
    29. // 创建PutObject请求。
    30. ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
    31. } catch (OSSException oe) {
    32. System.out.println("Caught an OSSException, which means your request made it to OSS, "
    33. + "but was rejected with an error response for some reason.");
    34. System.out.println("Error Message:" + oe.getErrorMessage());
    35. System.out.println("Error Code:" + oe.getErrorCode());
    36. System.out.println("Request ID:" + oe.getRequestId());
    37. System.out.println("Host ID:" + oe.getHostId());
    38. } catch (ClientException ce) {
    39. System.out.println("Caught an ClientException, which means the client encountered "
    40. + "a serious internal problem while trying to communicate with OSS, "
    41. + "such as not being able to access the network.");
    42. System.out.println("Error Message:" + ce.getMessage());
    43. } finally {
    44. if (ossClient != null) {
    45. ossClient.shutdown();
    46. }
    47. }
    48. //文件访问路径规则 https://BucketName.Endpoint/ObjectName
    49. StringBuilder stringBuilder = new StringBuilder("https://");
    50. stringBuilder
    51. .append(bucketName)
    52. .append(".")
    53. .append(endpoint)
    54. .append("/")
    55. .append(objectName);
    56. log.info("文件上传到:{}", stringBuilder.toString());
    57. return stringBuilder.toString();
    58. }
    59. }

    4. OSS工具类对象的创建

    1. package com.sky.config;
    2. import com.sky.properties.AliOssProperties;
    3. import com.sky.utils.AliOssUtil;
    4. import lombok.extern.slf4j.Slf4j;
    5. import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
    6. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
    7. import org.springframework.context.annotation.Bean;
    8. import org.springframework.context.annotation.Configuration;
    9. /**
    10. * 配置类,用于创建AliOssUtil对象
    11. */
    12. @Configuration
    13. @Slf4j
    14. public class OssConfiguration {
    15. // 通过参数注入的方式,将Oss的配置信息传递进来
    16. // Bean 如果容器中没有AliOssUtil对象,则创建AliOssUtil对象
    17. // ConditionalOnBean 表示如果容器中存在AliOssUtil对象,则不创建AliOssUtil对象
    18. @Bean
    19. @ConditionalOnMissingBean
    20. public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties) {
    21. log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
    22. // 创建AliOssUtil对象,并传入配置信息
    23. return new AliOssUtil(aliOssProperties.getEndpoint(),
    24. aliOssProperties.getAccessKeyId(),
    25. aliOssProperties.getAccessKeySecret(),
    26. aliOssProperties.getBucketName());
    27. }
    28. }

    5. 在Controller层编写文件上传逻辑

    1. // Autowired注解的作用:自动将匹配的Bean装配到@Autowired标注的变量、方法或构造函数上。(依赖注入)
    2. @Autowired
    3. private AliOssUtil aliOssUtil;
    4. /**
    5. * 文件上传
    6. * @param file
    7. * @return
    8. */
    9. @PostMapping("/upload")
    10. @ApiOperation("文件上传")
    11. public Result upload(MultipartFile file) {
    12. log.info("文件上传接口被调用:{}",file);
    13. String filePath = null;
    14. try {
    15. // 获取原始文件名
    16. String originalFilename = file.getOriginalFilename();
    17. // 截取原始文件名的扩展名
    18. String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
    19. // 生成新的文件名: UUID + 扩展名
    20. String newFileName = UUID.randomUUID().toString() + extName;
    21. // 文件上传请求路径
    22. filePath = aliOssUtil.upload(file.getBytes(), newFileName);
    23. }catch(IOException e){
    24. e.printStackTrace();
    25. log.error("文件上传失败:{}",e);
    26. return Result.error(MessageConstant.UPLOAD_FAILED);
    27. }
    28. return Result.success(filePath);
    29. }

    6. 测试(省略,做到这里基本无误了)

    接下来就来讲讲文件回显失败的几点调试方向

    文件回显失败的原因及其排查方向

    1. 检查你文件上传拼接的url是否正确

    这一步如果错了,实际上上传就已经错了,更别提回显这方面的事情了

    2. 首先,如果你全程跟着苍穹老师写的代码去做,必然会导致文件回显失败,我记得视频里面的代码最后是没有返回文件上传路径的,你可以改一下再尝试

    具体的,苍穹老师写的文件上传代码:

    问题就出在成功的时候还封装了错误的信息进行返回,你应该要把错误的返回放到catch中,成功后把文件路径放到Result中

    1. /**
    2. * 文件上传
    3. * @param file
    4. * @return
    5. */
    6. @PostMapping("/upload")
    7. @ApiOperation("文件上传")
    8. public Result upload(MultipartFile file) {
    9. log.info("文件上传接口被调用:{}",file);
    10. try {
    11. // 获取原始文件名
    12. String originalFilename = file.getOriginalFilename();
    13. // 截取原始文件名的扩展名
    14. String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
    15. // 生成新的文件名: UUID + 扩展名
    16. String newFileName = UUID.randomUUID().toString() + extName;
    17. // 文件上传请求路径
    18. String filePath = aliOssUtil.upload(file.getBytes(), newFileName);
    19. }catch(IOException e){
    20. e.printStackTrace();
    21. log.error("文件上传失败:{}",e);
    22. }
    23. return Result.error(MessageConstant.UPLOAD_FAILED);
    24. }
    3. 接着排查OSS,你得允许你的网页可以访问你的OSS对象存储服务之后才可以拿到文件的访问路径,使用OSS必须设置公共读属性

    由于我只是练习程序,不想麻烦所以直接设置了公共读写。但是其实最安全的方式还是配置一个防盗链放行你的网页会比较安全

  • 相关阅读:
    【QT ScrollArea】手势滑动ScrollArea窗口实现
    【大咖说Ⅲ】谢娟英教授:基于深度学习的野外环境下蝴蝶物种自动识别
    [UE笔记]客户端服务器时间同步
    系统方向学习9--android 10.0 去掉未知来源弹窗 默认授予安装未知来源权限
    这家公司因Log4j漏洞惨遭黑客攻击并勒索500万美元
    Python各文件类型对比: .py、.ipynb、.pyi、.pyc、.pyd
    Java设计模式之访问者模式
    Docker Compose命令讲解+文件编写
    1004 成绩排名
    Slurm作业管理系统常用命令和教程
  • 原文地址:https://blog.csdn.net/wzc200406/article/details/140329017