首页 > 其他分享 >【第12章】SpringBoot实战篇之文件上传(含阿里云OSS上传)

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

时间:2024-06-08 09:31:00浏览次数:29  
标签:实战篇 12 OSS RAM 访问 org import 上传 oss

文章目录


前言

本章节介绍本地文件上传和阿里云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 = "https://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 = "https://"+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,OSS,RAM,访问,org,import,上传,oss
From: https://blog.csdn.net/qq_44824164/article/details/139335099

相关文章

  • 【第11章】SpringBoot实战篇之文章(下)含条件分页
    文章目录前言一、文章列表查询1.ArticleController2.ArticleService二、文章查询1.ArticleController2.ArticleService三、文章更新1.ArticleController2.ArticleService四、文章删除1.ArticleController2.ArticleService五、文章列表查询(条件分页)1.Artic......
  • 【Python-因特网客户端编程-12】Python 提供了对 POP 和 IMAP 协议的支持
    Python提供了对POP和IMAP协议的支持一、使用Python代码与POP3和IMAP4邮件服务器进行通信使用`poplib`进行POP3操作示例:使用`poplib`获取邮件使用`imaplib`进行IMAP操作示例:使用`imaplib`获取邮件比较`poplib`和`imaplib`总结二、smtplib......
  • hdu1257最少拦截系统
    Dilworth定理通俗地讲就是对于一个偏序集,最少链划分等于最长反链长度。通俗点就是一个数列最少的不上升(<=)子序列的条数等于该数列最长上升(>)子序列的长度就是求最长有序子序列packagebag;importjava.util.Arrays;importjava.util.Scanner;publicclasshdu1257{......
  • Django上传图片时ImageField的max_length报错
    我使用的版本是Django4.2,有一个模型里定义了ImageField,以下面这个为例:classExample(models.Model)image=models.ImageField(blank=True,upload_to=my_image_path,)当我上传图片的时候,django返回了这样一个错误:Ensurethisfilenam......
  • [ABC126D] Even Relation 题解
    题意对一棵有$N$个点,$N-1$条边的树进行黑白染色,使得每两个距离为偶数的点颜色都一致。思路首先让我们回顾一下加法的性质:偶$+$偶$=$偶奇$+$奇$=$偶偶$+$奇$=$奇不难看出,距离为偶数的关系是可以传递的,而距离为奇数的关系不行。我们只需要做一遍dfs,对一个......
  • [ABC126F] XOR Matching 题解
    很好的构造题。题意请构造一个长度为$2^{m+1}$的序列$a$,该序列满足:$\foralli\in[1,2^{m+1}],a_i\in[0,2^m-1]$且每个数都恰好出现两次。对于任意一对$(i,j)$满足$a_i=a_j$,$a_i\oplusa_{i+1}\oplus\cdots\oplusa_{j-1}\oplusa_j=k$。$\oplus$表......
  • AcWing 1211:蚂蚁感冒 ← 模拟题
    【题目来源】https://www.acwing.com/problem/content/1213/【题目描述】长100厘米的细长直杆子上有n只蚂蚁。它们的头有的朝左,有的朝右。每只蚂蚁都只能沿着杆子向前爬,速度是1厘米/秒。当两只蚂蚁碰面时,它们会同时掉头往相反的方向爬行。这些蚂蚁中,有1只蚂蚁感冒......
  • Django 里实现表格内容上传
    先看效果图:当没有添加数据,就按提交键就会出现报错下面是操作步骤1.先在views.py文件里做添加#在views.pyclassAssetModelForm(forms.ModelForm):#newField=forms.CharField()classMeta:model=models.AssetSetfields=......
  • python自动化脚本:12306-火车票购票
    1.导包:importtimefromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.common.keysimportKeysfromselenium.webdriver.support.uiimportWebDriverWait2.选择浏览器驱动:这里选择的是Chromedriver=webdriver.Chrom......
  • Redis-12-SpringBoot集成Redis哨兵模式
    Redis哨兵的配置,参考我这篇文章:Redis-5-高可用1.背景网上搜半天没搜到份好用的,自己整理了下方便以后复制,基于springboot2.6.13。lettucecommons-pool22.集成2.1导入pom<!--spring-redis--><dependency><groupId>org.springframewor......