【第12章】SpringBoot实战篇之文件上传(含阿里云OSS上传)

作者 : admin 本文共4831个字,预计阅读时间需要13分钟 发布时间: 2024-06-8 共3人阅读

文章目录

  • 前言
  • 一、本地文件上传
  • 二、阿里云OSS上传
    • 1. 环境准备
    • 2.安装SDK
    • 3.使用长期访问凭证
      • 3.1 获取RAM用户的访问密钥
      • 3.2 配置RAM用户的访问密钥(Linux)
      • 3.3 从环境变量中获取RAM用户的访问密钥
    • 4. 工具类
    • 5.使用
  • 总结

前言

本章节介绍本地文件上传和阿里云OSS上传。


一、本地文件上传

package org.example.springboot3.bigevent.controller;

import org.example.springboot3.bigevent.entity.Result;
import org.springframework.web.bind.annotation.RequestMapping;
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;

/**
 * Create by zjg on 2024/5/30
 */
@RequestMapping("/file/")
@RestController
public class FileUploadController {
    @RequestMapping("upload")
    public Result upload(MultipartFile file) throws IOException {
        String filePath="E:\opt\file\upload\";
        String filename = file.getOriginalFilename();
        String pathname=filePath+ UUID.randomUUID()+filename.substring(filename.lastIndexOf("."));
        file.transferTo(new File(pathname));
        return Result.success("文件上传成功");
    }
}

二、阿里云OSS上传

1. 环境准备

使用Java 1.7.0及以上版本。

您可以通过命令java -version查看Java版本。

2.安装SDK

在Maven工程中使用OSS Java SDK,只需在pom.xml中加入相应依赖即可。在中加入如下内容:

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.1</version>
</dependency>

如果使用的是Java 9及以上的版本,则需要添加JAXB相关依赖。添加JAXB相关依赖示例代码如下:

<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>

3.使用长期访问凭证

配置RAM用户的访问密钥:如果您需要长期访问您的OSS,您可以通过RAM用户的访问密钥的方式访问您的OSS。

3.1 获取RAM用户的访问密钥

如何获取RAM用户的访问密钥,请参见创建RAM用户的AccessKey。

3.2 配置RAM用户的访问密钥(Linux)

  1. 打开终端
  2. 执行以下命令
sudo vim /etc/profile
  1. 在文件末尾添加RAM用户的访问密钥
export OSS_ACCESS_KEY_ID=LTAI****
export OSS_ACCESS_KEY_SECRET=IrVTNZNy**** 
  1. ESC键退出编辑模式,输入:wq,然后按Enter键保存并退出文件
  2. 输入以下命令以使更改生效
source /etc/profile
  1. 执行以下命令验证环境变量配置
echo $OSS_ACCESS_KEY_ID
echo $OSS_ACCESS_KEY_SECRET

成功返回示例如下:

LTAI****
IrVTNZNy****

3.3 从环境变量中获取RAM用户的访问密钥

// 使用环境变量中获取的RAM用户的访问密钥配置访问凭证。
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

4. 工具类

package org.example.springboot3.bigevent.utils;

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.InputStream;

public class OssUtil {
    private static final String ENDPOINT = "http://oss-cn-beijing.aliyuncs.com";
    private static final String BUCKET_NAME = "oss";

    //上传文件,返回文件的公网访问地址
    public static String uploadFile(String objectName, InputStream inputStream) throws com.aliyuncs.exceptions.ClientException {
        // 使用环境变量中获取的RAM用户的访问密钥配置访问凭证。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT,credentialsProvider);
        //公网访问地址
        String url = "";
        try {
            // 创建存储空间。
            ossClient.createBucket(BUCKET_NAME);
            ossClient.putObject(BUCKET_NAME, objectName, inputStream);
            url = "http://"+BUCKET_NAME+"."+ENDPOINT.substring(ENDPOINT.lastIndexOf("/")+1)+"/"+objectName;
        } 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();
            }
        }
        return url;
    }
}

5.使用

package org.example.springboot3.bigevent.controller;

import com.aliyuncs.exceptions.ClientException;
import org.example.springboot3.bigevent.entity.Result;
import org.example.springboot3.bigevent.utils.OssUtil;
import org.springframework.web.bind.annotation.RequestMapping;
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;

/**
 * Create by zjg on 2024/5/30
 */
@RequestMapping("/file/")
@RestController
public class FileUploadController {
    @RequestMapping("oss/upload")
    public Result<String> ossUpload(MultipartFile file) throws IOException, ClientException {
        String filename = file.getOriginalFilename();
        String pathname= UUID.randomUUID()+filename.substring(filename.lastIndexOf("."));
        String url = OssUtil.uploadFile(pathname, file.getInputStream());
        return Result.success("文件上传成功",url);
    }
}


总结

该方案仅供参考,更多内容请参考官方网站

回到顶部
阿里云
快速入门
API & SDK
开发者工具

本站无任何商业行为
个人在线分享 » 【第12章】SpringBoot实战篇之文件上传(含阿里云OSS上传)
E-->