阿里云OSS实现图片上传

1、表单提交:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>

    <form action="/upload" method="post" enctype="multipart/form-data">
        姓名: <input type="text" name="username"><br>
        年龄: <input type="text" name="age"><br>
        头像: <input type="file" name="file"><br>
        <input type="submit" value="提交">
    </form>

</body>
</html>

重点:
method="post" 
enctype="multipart/form-data"
<input type="file"

2、阿里云准备

  1. 支付宝登录阿里云官网

  2. 通过控制台搜索找到对象存储OSS服务

  3. 开通OSS服务,进入对象存储

  4. Bucket列表、创建一个Bucket(桶)

  5. 配置AK & SK:

    • 点击个人头像,AccessKey管理

    • 点击 “AccessKey”

      //记得先修改OSS_ACCESS_KEY_ID与OSS_ACCESS_KEY_SECRET后面的值
      //配置系统的环境变量。
      set OSS_ACCESS_KEY_ID=LTAI5tCdGAJZ6x77Ldcy15V1
      set OSS_ACCESS_KEY_SECRET=Rimg3irytHVeRkQLtMn3J2vFIMOaYu
      
      //让更改生效。
      setx OSS_ACCESS_KEY_ID "%OSS_ACCESS_KEY_ID%"
      setx OSS_ACCESS_KEY_SECRET "%OSS_ACCESS_KEY_SECRET%"
      
      //验证环境变量是否生效。
      echo %OSS_ACCESS_KEY_ID%
      echo %OSS_ACCESS_KEY_SECRET%
      

3、快速入门

官网参考地址

<!--aliyun oss 对象存储服务-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.17.4</version>
</dependency>

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.3</version>
</dependency>
package com.example;

/**
 * @author jx
 * @version 1.0
 * @since 2024/10/10 17:48
 */
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.InputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";//修改1
        // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "tlias-xiaojiang";//修改2
        // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "3.jpg";//oos中的名字 //修改3

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

        try {
            String content = "D:\\MyFiles\\Blog\\md\\test\\1.jpg";//上传图片的地址  //修改4
            InputStream inputStream = new FileInputStream(content);//新建流对象
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(inputStream.readAllBytes()));
        } 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();
            }
        }
    }
}

#文件上传配置
#配置单个文件最大上传大小
spring.servlet.multipart.max-file-size=10MB
#配置单个请求最大上传大小(一次请求可以上传多个文件)
spring.servlet.multipart.max-request-size=100MB

4、项目使用

1、引入工具类
package com.example.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.util.UUID;

/**
 * 阿里云OSS操作工具类
 */
@Slf4j
public class AliyunOSSUtils {

    /**
     * 上传文件
     * @param endpoint endpoint域名
     * @param bucketName 存储空间的名字
     * @param content 内容字节数组
     */
    public static String upload(String endpoint, String bucketName, byte[] content, String extName) throws Exception {
        // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = UUID.randomUUID() + (extName.contains(".")?"":".") +extName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new ByteArrayInputStream(content));
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, but was rejected with an error response for some reason.");
            log.error("Error Message:" + oe.getErrorMessage());
            log.error("Error Code:" + oe.getErrorCode());
            log.error("Request ID:" + oe.getRequestId());
            log.error("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            log.error("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.");
            log.error("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
    }

}

2、自定义配置文件
package com.example.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@Data
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOSSPropertie {
    private String myEndpoint;
    private String myBucketName;

}

3、配置文件添加配置
#阿里云OSS配置信息
aliyun.oss.my-endpoint=https://oss-cn-shanghai.aliyuncs.com
aliyun.oss.my-bucket-name=tlias-xiaojiang
4、controller使用
package com.example.controller;

import cn.hutool.core.io.FileUtil;
import com.example.config.AliyunOSSPropertie;
import com.example.pojo.Result;
import com.example.util.AliyunOSSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UpLoadController {
    /*
    2、配置文件读取
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName;
    */


    //3、自定义配置文件读取
    @Autowired
    private AliyunOSSPropertie aliyunOSSPropertie;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws Exception {
        System.out.println("upload () .........................");
        /*
        1、直接写入配置
        //Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-shanghai.aliyuncs.com";
        //填写Bucket名称,例如examplebucket。
        String bucketName = "tlias-xiaojiang";
          */
        String endpoint = aliyunOSSPropertie.getMyEndpoint();
        String bucketName = aliyunOSSPropertie.getMyBucketName();

        //获取文件名称
        String filename = file.getOriginalFilename();

        //获取文件后缀名
        String extName = FileUtil.extName(filename);


        String url = AliyunOSSUtils.upload(endpoint, bucketName, file.getBytes(), extName);
        //当前路径返回,前端无法访问,浏览器的安全策略不允许直接加载本地文件资源。
        return Result.success(url);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值