Java-Ali图片上传实现

2023-12-13 18:40:38

0.application.yml文件中编写配置

sky:
  alioss: 地域节点(概览查看)
    endpoint: 
    access-key-id: 密钥账号
    access-key-secret: 密钥密码
    bucket-name: Bucket名称

1.导入依赖

<!--阿里云对象存储-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.5.0</version>
</dependency>

2.导入工具类

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.ObjectMetadata;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "sky.alioss")
public class AliOssUtil {

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

    /**
     * 文件上传
     *
     * @param fileName
     * @param inputStream
     * @return
     */
    public String upload(String fileName, InputStream inputStream) {

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

        String objectName = "images/" + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                + "/" + System.currentTimeMillis() +"-"+fileName;
        try {
            //解决图片预览问题(默认是下载)
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(getContentType(fileName.substring(fileName.lastIndexOf("."))));

            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, inputStream,metadata);
        } catch (OSSException oe) {
            System.out.println("Error Message:" + oe.getErrorMessage());
        } catch (ClientException ce) {
            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();
    }

    private 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/jpg";
        }
        return "image/jpg";
    }
}

3.导入Controller

import com.itheima.entity.Result;
import com.itheima.util.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/brand/upload")
@Slf4j
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    //文件上传
    @PostMapping
    public Result upload(MultipartFile file) throws IOException {
        String path = aliOssUtil.upload(file.getOriginalFilename(), file.getInputStream());
        log.info("图片上传之后的访问路径是{}", path);
        return Result.success(path);
    }
}

文章来源:https://blog.csdn.net/m0_60388241/article/details/134975882
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。