首页 > 基础资料 博客日记

实现 文件上传【头像/图片】

2024-08-23 17:00:06基础资料围观115

本篇文章分享实现 文件上传【头像/图片】,对你有帮助的话记得收藏一下,看Java资料网收获更多编程知识

实现 文件上传【头像/图片】

浏览器---->后端服务----->阿里云OSS

工具类

@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {

    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);

        log.info("文件上传到:{}", stringBuilder.toString());

        return stringBuilder.toString();
    }
}

代码实现

  1. 在application.yml中编写相关信息

    sky:
      alioss:
        endpoint: oss-cn-hangzhou.aliyuncs.com
        access-key-id: LTAI5tJKk5H21ZmQQ9CgeG8y
        access-key-secret: 90xHhXxKqg6LNnbb4ubp1BeIdw7RAT
        bucket-name: sky-zy2596
    
  2. 编写AliOssProperties ,将yml文件信息映射到AliOssProperties对象中

    @Component
    @ConfigurationProperties(prefix = "sky.alioss")
    @Data
    public class AliOssProperties {
    
        private String endpoint;
        private String accessKeyId;
        private String accessKeySecret;
        private String bucketName;
    
    }
    
  3. 编写配置类,创建AliOssUtil对象

    /**
     * 配置类,用于创建AliOssUtil对象
     */
    @Configuration
    @Slf4j
    public class OssConfiguration {
    
        @Bean
        @ConditionalOnMissingBean//保证spring容器只有一个AliOssUtil对象
        public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties ){//将aliOssProperties 中的属性赋给AliOssUtil对象
            log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
            return new AliOssUtil(aliOssProperties.getEndpoint()
                    ,aliOssProperties.getAccessKeyId()
                    ,aliOssProperties.getAccessKeySecret()
                    ,aliOssProperties.getBucketName());
    
        }
    }
    
  4. 编写文件上传接口

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){// file 这里的参数名必须和前端提交的参数名保持一致
        log.info("文件上传:{}",file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
    
        } catch (IOException e) {
            log.error("文件上传失败:{}",e);
        }
           return Result.error("文件上传失败");
    }
    

文章来源:https://www.cnblogs.com/zydevelop/p/18376390/zy_upload
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云