阿里云上传文件

简介: 阿里云上传文件

 阿里云上传文件1(未分模块)

1、pom文件加入依赖

<!--阿里云 OSS 依赖-->
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.1</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>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
<dependency>
    <groupId>org.jetbrains</groupId>
    <artifactId>annotations</artifactId>
    <version>RELEASE</version>
    <scope>compile</scope>
</dependency>

image.gif

2、配置yam

这个写自己的身份id-密钥-桶名

# 阿里云相关配置
aliyun:
  oss:
    # 外网访问路径
    endpoint: http://oss-cn-beijing.aliyuncs.com
    # 身份id
    accessKeyId: LTAI5tS4GcnjVmnp
    # 密钥
    accessKeySecret: s2ioVYtO5bqhwluSJMvkx
    # 桶名
    bucketName: zsh33

image.gif

3、引入工具类

package com.zsh.springboot_webtwo.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
@ConfigurationProperties(prefix = "aliyun.oss")
@Data
@Component
public class AliOSSUtils {
//    @Value("${aliyun.oss.endpoint}")
    private String endpoint;    // 外网访问路径
//    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;    // 身份id
//    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;  // 密钥
//    @Value("${aliyun.oss.bucketName}")
    private String bucketName;  // 桶名
    /**
     * 实现上传图片到OSS
     */
    public String upload(@org.jetbrains.annotations.NotNull MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();
        // 避免文件覆盖
        String originalFilename = multipartFile.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的路径返回
    }
}

image.gif

4、Controller 文件上传

package com.zsh.springboot_webtwo.controller;
import com.itheima.springboot_webtwo.utils.AliOSSUtils;
import com.itheima.springboot_webtwo.utils.Result;
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;
@RestController
public class UploadController {
    @Autowired
    private AliOSSUtils aliOSSUtils;
    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        String url = aliOSSUtils.upload(image);
        return Result.success(url);
    }
}

image.gif

阿里云上传文件2(分模块)

1、定义OSS相关配置

在zsh-server模块

application-dev.yml

zsh:
  alioss:
    endpoint: oss-cn-hangzhou.aliyuncs.com
    access-key-id: LTAI5tPeFLzsPPT8gG3LPW64
    access-key-secret: U6k1brOZ8gaOIXv3nXbulGTUzy6Pd7
    bucket-name: zsh-take-out

image.gif

application.yml

spring:
  profiles:
    active: dev    #设置环境
zsh:
  alioss:
    endpoint: oss-cn-beijing.aliyuncs.com
    access-key-id: LTAIGcnmnp
    access-key-secret: s2iohwOUMvkx
    bucket-name: zsh33

image.gif

2、读取OSS配置

在zsh-common模块中,已定义

package com.zsh.properties;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "zsh.alioss")
@Data
public class AliOssProperties {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
}

image.gif

3、生成OSS工具类对象

在zsh-server模块

package com.zsh.config;
import com.zsh.properties.AliOssProperties;
import com.zsh.utils.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
 * 配置类,用于创建AliOssUtil对象
 */
@Configuration
@Slf4j
public class OssConfiguration {
    @Bean
    @ConditionalOnMissingBean
    public AliOssUtil aliOssUtil(AliOssProperties aliOssProperties){
        log.info("开始创建阿里云文件上传工具类对象:{}",aliOssProperties);
        return new AliOssUtil(aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret(),
                aliOssProperties.getBucketName());
    }
}

image.gif

AliOssUtil.java在zsh-common模块中定义

package com.zsh.utils;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayInputStream;
@Data
@AllArgsConstructor
@Slf4j
public class AliOssUtil {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;
    /**
     * 文件上传
     *
     * @param bytes
     * @param objectName
     * @return
     */
    public String upload(byte[] bytes, String objectName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            // 创建PutObject请求。
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        } 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();
            }
        }
        //文件访问路径规则 https://BucketName.Endpoint/ObjectName
        StringBuilder stringBuilder = new StringBuilder("https://");
        stringBuilder
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);
        log.info("文件上传到:{}", stringBuilder.toString());
        return stringBuilder.toString();
    }
}

image.gif

4、定义文件上传接口

在zsh-server模块中定义接口

package com.zsh.controller.admin;
import com.zsh.constant.MessageConstant;
import com.zsh.result.Result;
import com.zsh.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;
/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传:{}",file);
        try {
            //原始文件名
            String originalFilename = file.getOriginalFilename();
            //截取原始文件名的后缀   dfdfdf.png
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            //构造新文件名称
            String objectName = UUID.randomUUID().toString() + extension;
            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败:{}", e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }
}

image.gif


相关实践学习
对象存储OSS快速上手——如何使用ossbrowser
本实验是对象存储OSS入门级实验。通过本实验,用户可学会如何用对象OSS的插件,进行简单的数据存、查、删等操作。
相关文章
|
Linux iOS开发 开发者
探索FFmpeg:实现自定义播放速度的全方位指南(一)
探索FFmpeg:实现自定义播放速度的全方位指南
2025 0
|
存储 前端开发 JavaScript
ahooks 正式发布:值得拥抱的 React Hooks 工具库
ahook定位于一套基于 React Hooks 的工具库,核心围绕 React Hooks 的逻辑封装能力,降低代码复杂度和避免团队的重复建设为背景,共同建设和维护阿里经济体层面的 React Hooks 库。
24610 1
ahooks 正式发布:值得拥抱的 React Hooks 工具库
|
9月前
|
存储 人工智能 API
阿里云/本地部署OpenClaw+免费大模型接入,龙虾AI创业低门槛入场、商业化方向完整解析
OpenClaw并非只是一款本地AI对话工具,而是一套可自托管、可扩展、可商业化的AI智能体基础设施,具备私有化部署、多渠道接入、Skill插件化、多Agent协同四大核心能力。当前市场呈现需求爆发与供给不足的明显缺口,大量中小企业与行业场景亟需轻量化、安全、可控的AI解决方案,这也让OpenClaw成为2026年个人与小型团队低成本创业的优质载体。本文完整拆解6类已验证的商业化路径,同时提供2026年阿里云、MacOS、Linux、Windows11全平台部署流程、阿里云百炼Coding Plan免费大模型API配置,以及全场景常见问题解决方案,所有命令可直接复制运行,无营销表述,适合零基础
1067 1
|
9月前
|
JavaScript Linux API
OpenClaw部署保姆级攻略:阿里云无影云电脑+本地系统+Skills集成+API配置实操手册
OpenClaw(又名Clawdbot)是2026年主流的开源AI自动化代理工具,主打本地优先、隐私可控、任务可执行的核心特性,区别于普通对话式AI,可通过集成各类Skills技能,完成文件处理、网页自动化、办公辅助、信息提取等实际操作,无需依赖第三方平台托管。本文聚焦2026年最新部署方案,完整覆盖阿里云无影云电脑云端部署、本地Windows11/MacOS/Linux系统部署两大核心场景,同步详解Skills技能安装与管理、阿里云百炼Coding Plan免费大模型API配置流程,搭配高频问题排查方案,帮助零基础用户全程顺畅完成部署与使用,全程无额外付费门槛,操作可复现。
624 1
|
8月前
|
人工智能 JSON 测试技术
手写一个自动断言Skill:30行代码,省你每天2小时
测试正悄然变革:AI加速编码,手工断言却成交付瓶颈。30行代码实现自动断言——基于响应结构智能生成存在性、类型、范围等规则断言,适配微服务与AI生成代码的快速迭代,将断言维护从小时级降至秒级。
|
8月前
|
人工智能 自然语言处理 安全
OpenClaw 与飞书绑定实操教程:企业IM接入AI服务一步到位
本文详解OpenClaw与飞书集成实操:从飞书开放平台获取App ID/Secret,到OpenClaw后台配置绑定,全程图文指引;涵盖常见报错排查与安全提示,助力企业5分钟完成AI服务接入,实现IM内即用智能问答、内容生成等能力。
|
弹性计算
查看阿里云服务器IP地址的三种方法
查看阿里云服务器IP地址的三种方法
8730 1
|
11月前
|
SQL 自然语言处理 数据挖掘
2026年BI行业深度盘点:Chat BI 从“被动看数”到“主动问数”的范式重构
2026年,传统BI遭遇瓶颈,企业亟需突破操作门槛、分析深度与数据孤岛三大痛点。对话式智能BI应运而生,以自然语言交互、深度语义理解与主动决策建议为核心,重塑数据分析范式。Quick BI 智能小Q 凭借“NL2SQL大模型+企业级数据引擎”双轮驱动,实现96.5%复杂SQL生成准确率,支持多源数据连接、垂直场景增强与企业级安全管控,真正让业务人员“开口问数”,获得可执行洞察,推动“人人都是分析师”的时代到来。
|
11月前
|
SQL 数据挖掘 BI
Python处理Excel多工作表:openpyxl与pandas的实战对比
本文对比openpyxl与pandas在处理Excel多工作表时的性能差异,结合真实电商案例揭示二者核心定位:openpyxl擅长精细格式控制,pandas专注高效数据处理。通过读写实测、典型场景与混合策略,提供选型决策树,助你提升数据处理效率数十倍。
1063 0
|
资源调度 JavaScript 前端开发
yarn源|yarn 国内镜像+linux删除大量文件
yarn源|yarn 国内镜像yarn源|yarn 国内镜像+linux删除大量文件
1919 1