Java 文件上传-阿里云OSS对象存储

一. 简介

  1. 文件上传;指将本地图片、视频、音频等文件上传到服务器,供其他用户浏览或下载的过程

二. 本地存储

java 复制代码
@Slf4j
@RestController
public class UploadController {

    @PostMapping("/upload")
    public Result upload(String username, Integer age, MultipartFile file) throws IOException {

        log.info("接收参数{},{},{}",username,age,file);
        //获取原始文件名
        String originalFilename =  file.getOriginalFilename();

        //获取原始文件名的扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成新的唯一的文件名
        String newFileName = UUID.randomUUID().toString() + extension;
        //保存文件
        file.transferTo(new File("D:/image/" + newFileName));

        return Result.success();
    }
html 复制代码
<!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>

三. 配置文件上传大小

  1. 上传文件时,默认上传文件的最大大小为1MB,超过1MB需要在配置文件中配置

四. 阿里云OSS

1. 介绍

阿里云是阿里巴巴集团旗下全球领先的云计算公司,也是国内最大的云服务提供商。

阿里云对象存储OSS(Object Storage Service),是一款海量、安全、低成本、高可靠的云存储服务,使用OSS,您可以通过网络随时存储和调用包括文本、图片、音频和视频等在内的各种文件。

2. 注册阿里云

3. 充值

4. 开通对象存储服务

5. 创建Bucket

6. 获取并配置AccessKey(秘钥)

五. 注意 注意 注意

六. 阿里云OSS-入门程序-pom依赖引入

  1. 注意:在使用第三方提供的云服务或技术时,一定要参照对应的官方文档进行开发和测试

注意:环境变量配置成功后重启idea,进行测试程序编写

七. 程序-测试文件上传

java 复制代码
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import java.io.*;
import java.nio.file.Files;


public class OssJavaSdkQuickStart {


    public static void main(String[] args) throws com.aliyuncs.exceptions.ClientException {
        // Endpoint以华东1(杭州)为例,填写为https://oss-cn-hangzhou.aliyuncs.com,其它Region请按实际情况填写。
        
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String bucketName = "wyyzs-java-file";
        // 填写Bucket所在地域。以华东1(杭州)为例,Region填写为cn-hangzhou。
        String region = "cn-beijing";

        // 从环境变量中获取访问凭证。运行本代码示例之前,请先配置环境变量
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

        // 创建OSSClient实例。
        // 当OSSClient实例不再使用时,调用shutdown方法以释放资源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 显式声明使用 V4 签名算法
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        try {
            // 1. 创建存储空间(Bucket)
            ossClient.createBucket(bucketName);
            System.out.println("1. Bucket " + bucketName + " 创建成功。");
            // 2. 上传文件
            File file = new File("D:\\照片\\swk.webp");
            byte[] content = Files.readAllBytes(file.toPath());

            String objectName = "swk.webp";
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
            System.out.println("2. 文件 " + 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 | IOException 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();
            }
        }
    }
}

八. 参数化配置

1. @Value("${key}")

指将一些需要灵活变化的参数,配置在配置文件中,然后通过@Value注解来注入外部配置的属性。

2. @ConfigurationProperties

使用@Value注解注入配置文件的配置项,如果配置项多,注入繁琐,不便于维护管理和复用

相关推荐
rannn_1114 小时前
【力扣hot100】链表专题|160、206、234、141、142
java·算法·leetcode·链表·面试·开发
IKUN家族5 小时前
Spring IoC&DI
java·spring·rpc
山荷枝6 小时前
03-框架--Spring
java·后端·spring
ChaHae-In7 小时前
SpringBoot统一功能处理
java·spring boot·后端
coder!mq7 小时前
说几个常见的语法糖?
java·开发语言·算法
gugucoding7 小时前
38. 【Java】Stream API(下):高级操作与性能
java·开发语言
心平气和量大福大8 小时前
android-实例-蒲公英-更新与安装-5-签名与生成APK
android·java·开发语言
952368 小时前
Spring-cloud配置中心
java·spring·spring cloud·微服务
ydd1001009 小时前
寻找两个正序数组的中位数 Java 题解,二分分割详解
java·开发语言
真上帝的左手10 小时前
10. 软件设计&架构-Spring Security 7 整合CAS SSO 单点登录
java·spring·架构·sso