SpringBoot文件上传-阿里云OSS

2023-09-20 10:28:14

1.打开阿里云

说明:登录阿里云账号

2.点击AccessKey管理

 3.创建AccessKey

说明:记得复制accessKeyId,accessKeySecret并保存起来

4. 点击对象存储OSS

5.创建Bucket

说明:创建储存桶 

 

6.查看SDK示例

 7.Java简单上传

8.上传文件流

说明:以上传图片为例

 9.copy代码

说明:由于新版要配置环境变量(为了安全),因此修改官方了代码.

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 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-hangzhou.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = "exampledir/exampleobject.txt";
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        String filePath= "D:\\localpath\\examplefile.txt";

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

        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } 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();
            }
        }
    }
} 

更正

package com.itheima;

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.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.InputStream;
@Component
public class Demo {
@Value("${accessKeyId}")
    public static void main(String[] args) throws Exception {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "******";
        String accessKeyId="*****";
        String accessKeySecret="******";
        
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "web-forever";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = "1.jpg";
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件流。
        String filePath= "C:\\Users\\Lenovo\\Desktop\\cStudy\\logo.png";

        // 创建OSSClient实例。
//        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        } 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();
            }
        }
    }
} 

 10.endpoint

11.工具类

说明:创建工具类文件节utils

 

 12.编写工具类

package com.itheima.controller.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component
public class AliOSSUtils {
//    value注入外部属性
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId ;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret ;
    @Value("${aliyun.oss.bucketName}")
    private String bucketName ;

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();
        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}

13.配置application.properties

#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/tlias
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=123456
#配置mybatis的日志, 指定输出到控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#开启mybatis的驼峰命名自动映射开关 a_column ------> aCloumn
mybatis.configuration.map-underscore-to-camel-case=true
#配置上传文件的大小限制
spring.servlet.multipart.max-file-size=10MB
#配置单个请求的最大 大小的限制(一次请求中是可以上传多个文件)
spring.servlet.multipart.max-request-size=100MB
#自定义的阿里云OSS配置信息

aliyun.oss.endpoint=****************
aliyun.oss.accessKeyId=****************
aliyun.oss.accessKeySecret=****************
aliyun.oss.bucketName=****************

14.控制类

 说明:编写UploadController类 

package com.itheima.controller;

import com.itheima.controller.utils.AliOSSUtils;
import com.itheima.pojo.Result;
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.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Slf4j
@RestController
public class UploadController {
    @Autowired
   private AliOSSUtils aliOSSUtils;

    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传,文件名:{}", image.getOriginalFilename());
//        调用阿里云工具类
      String url=aliOSSUtils.upload(image);
      log.info("文件上传成功,文件访问的url:{}",url);
      return  Result.success(url);
    }
}

15.启动类

16.测试

 

 

更多推荐

Python爬虫有哪些库,分别怎么用

目录Python常用爬虫库代码示例requests+BeautifulSoupScrapySeleniumPyQueryAxiosrequests-htmlpyppeteer总结Python是一种非常流行的编程语言,因其易学易用和广泛的应用而受到开发者的喜爱。在Python中,有许多库可以用于爬虫程序的开发,这些库可以

第9章 【MySQL】InnoDB的表空间

表空间是一个抽象的概念,对于系统表空间来说,对应着文件系统中一个或多个实际文件;对于每个独立表空间来说,对应着文件系统中一个名为表名.ibd的实际文件。大家可以把表空间想象成被切分为许许多多个页的池子,当我们想为某个表插入一条记录的时候,就从池子中捞出一个对应的页来把数据写进去。9.1温习9.1.1页面类型InnoDB

VINS中的初始化方法

背景本文档介绍VINS中常见的初始化方法,静态初始化相对简单,通常1s内可以完成,但如果遇到在运动时的初始化问题,初始化难度相对较大,实际工程问题中,通常会将初始化分为静态和动态初始化两部分,这里主要是介绍动态初始化方案。一、基础知识:IMUPreintegrationIMUPreintegration等式两边同时乘以

19 视图定义 union 是根据第一个 select 字段列表顺序,来进行 merge 的

前言这个问题主要是在之前存在这样的一个问题,在生产环境上面按照我的直观理解,mysql应该是根据key进行merge,所以select的顺序应该是“不重要”??,但是结果我理解错了然后线上的查询也出现了问题,发现很奇怪的问题,明明key01列是id,但是有一部分key01是field1,然后进而产生了业务上面的查询问题

【多线程案例】单例模式

单例模式是设计模式的一种,先谈谈什么是设计模式?大家应该都知道棋谱、剑谱之类的,就是一些“高手”在经历过长期的累计之后,更具经验写出的具有固定套路的处理“方法”,只要按照这个套路来,在对局之中必然是不会吃亏的,甚至能够一招制敌。那么在我们日常的开发中也有大佬们针对一些十分常见的场景,抽象出固定的套路。一些小白在学习了大

Spark的基础

实训笔记--Spark的基础Spark的基础一、Spark的诞生背景二、Spark概念2.1SparkCore2.2.SparkSQL2.3SparkStreaming2.4SparkMLlib2.5SparkGraphX2.6SparkR三、Spark的特点3.1计算快速3.2易用性3.3兼容性3.4通用性四、Spa

Java IO 之 BIO、NIO 和 AIO

一、IOIO是Input和Output二词的缩写,意为输入和输出,直接来说,实现一般的I/O是没有什么难度的,但涉及到多线程时,要解决I/O的问题就不是一个简单的事情了,会涉及到同步和异步的问题,阻塞和非阻塞的问题。1.1同步和异步同步可以借用多线程来方便理解,多条线程,从字面意思上来看,当他们在同一直线上时,就是同步

mysql---视图详解

提示:视图最大的优点用来协助用户提高查询效力以及保护数据安全文章目录视图视图的作用:创建视图单表创建视图多表创建视图查看视图更新视图数据修改视图删除视图视图视图(View)是一个虚拟表,其内容由select查询定义。同真实的表一样,是一个select查询的结果集,所有数据来源于基表视图其实就是一个select返回的结果

写一篇nginx配置指南

nginx.conf配置找到Nginx的安装目录下的nginx.conf文件,该文件负责Nginx的基础功能配置。配置文件概述Nginx的主配置文件(conf/nginx.conf)按以下结构组织:配置块功能描述全局块与Nginx运行相关的全局设置events块与网络连接有关的设置http块代理、缓存、日志、虚拟主机等

分布式电源接入对配电网影响分析(Matlab代码实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。⛳️座右铭:行百里者,半于九十。📋📋📋本文目录如下:🎁🎁🎁目录💥1概述📚2运行结果🎉3参考文献🌈4Matlab代码、数据、文章💥1概述分布式电源的接入将配电系统从传统的无源放射

极简解析!IP计费的s5爬虫IP

大家好!今天我将为大家分享关于s5爬虫IP服务的知识。对于经常做爬虫的小伙伴来说,需要大量的爬虫IP支持爬虫业务,那么对于选择什么样的爬虫IP,我想我有很多发言权。下面我们一起了解下IP计费的s5爬虫IP的知识,废话不多说,让我们开始吧!第一部分:了解s5爬虫和IP计费首先,让我们简单了解一下s5爬虫和IP计费是什么。

热文推荐