阿里云上传文件

本文涉及的产品
对象存储 OSS,20GB 3个月
对象存储 OSS,恶意文件检测 1000次 1年
对象存储 OSS,内容安全 1000次 1年
简介: 阿里云上传文件

 阿里云上传文件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搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
相关文章
|
7天前
|
存储 PHP 文件存储
32 单文件上传
路老师分享PHP文件上传教程,涵盖配置php.ini、使用$_FILES变量和move_uploaded_file()函数等关键步骤,帮助你轻松实现单文件上传功能。纯干货,技术知识分享。
22 1
|
11天前
|
Java
smartupload文件上传!
使用 `smartupload.jar` 实现文件上传和下载。首先将 `smartupload.jar` 添加到项目中,然后创建上传页面,确保表单使用 `POST` 方法并设置 `enctype=&quot;multipart/form-data&quot;`。接着在服务器端通过 `SmartUpload` 对象处理文件上传,保存文件到指定目录,并获取表单中的其他数据。最后,实现文件下载功能,设置响应头以触发浏览器下载文件。
20 0
|
存储 移动开发 JavaScript
|
对象存储
从零玩转文件上传之七牛云1
从零玩转文件上传之七牛云
130 0
|
缓存 网络安全 对象存储
从零玩转文件上传之七牛云2
从零玩转文件上传之七牛云
85 0
|
安全 应用服务中间件 PHP
[SUCTF 2019]CheckIn(文件上传)
[SUCTF 2019]CheckIn(文件上传)
165 0
|
前端开发
前端上传文件或者上传文件夹
前端上传文件或者上传文件夹
246 0
前端上传文件或者上传文件夹
|
开发者
上传文件到服务器 | 学习笔记
快速学习上传文件到服务器。
135 0
上传文件到服务器 | 学习笔记
|
数据安全/隐私保护 Windows
J3
|
存储 Java 应用服务中间件
阿里 OSS 文件上传,别再说你不会上传文件了。
阿里 OSS 文件上传,别再说你不会上传文件了。
J3
4691 0
阿里 OSS 文件上传,别再说你不会上传文件了。