OSS简单文件上传和本地存储上传

发布时间 2023-06-12 21:41:28作者: 菠菜好不好吃

网站的文件上传方法

本地存储上传

// 本地存储方式   MultipartFile接受文件
    @PostMapping("/save")
    public Result save(String username, Integer age, MultipartFile image) throws IOException {
        log.info("文件:{}, {}, {}", username, age, image);

        String or = image.getOriginalFilename();
        // UUID.randomUUID()获取一个独一无二的文件名字   or.substring(or.indexOf(".")获取文件后缀名
        String name = UUID.randomUUID().toString() + or.substring(or.indexOf("."));
        // 存储的本地文件目录
        image.transferTo(new File("E:/WYW/" + name));

        return Result.success();
    }

阿里云对象存储OSS实现文件上传

OOS

阿里云对象存储OSS(Object Storage Service)为您提供基于网络的数据存取服务。使用OSS,您可以通过网络随时存储和调用包括文本、图片、音视频在内的各类数据文件。

Maven注入依赖

<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.1</version>
</dependency>

如果使用的是Java 9及以上的版本,则需要添加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>

Controller层

@PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传:{}", image.getOriginalFilename());

        // 调用阿里云OSS工具类,将上传的文件上传到阿里云
        String url = aliOSSUtils.upload(image);

        // 封装 响应
        return Result.success(url);
    }

AliOSSUtils工具类

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Configuration
public class AliOSSUtils {

    // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
    private String accessKeyId = "yourAccessKeyId";
    private String accessKeySecret = "yourAccessKeySecret";
    // 填写Bucket名称,例如examplebucket。
    private String bucketName = "examplebucket";

    /**
     * 实现上传图片到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的路径返回
    }

}

UploadController层完整代码

import com.wyw.tlias_w.pojo.Result;
import com.wyw.tlias_w.util.AliOSSUtils;
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;

    // 本地存储方式   MultipartFile接受文件
//    @PostMapping("/save")
//    public Result save(String username, Integer age, MultipartFile image) throws IOException {
//        log.info("文件:{}, {}, {}", username, age, image);
//
//        String or = image.getOriginalFilename();
//        // UUID.randomUUID()获取一个独一无二的文件名字   or.substring(or.indexOf(".")获取文件后缀名
//        String name = UUID.randomUUID().toString() + or.substring(or.indexOf("."));
//        // 存储的本地文件目录
//        image.transferTo(new File("E:/WYW/" + name));
//
//        return Result.success();
//    }

    @PostMapping("/upload")
    public Result upload(MultipartFile image) throws IOException {
        log.info("文件上传:{}", image.getOriginalFilename());

        // 调用阿里云OSS工具类,将上传的文件上传到阿里云
        String url = aliOSSUtils.upload(image);
        System.out.println(url);

        // 封装 响应
        return Result.success(url);
    }
}

转载:https://help.aliyun.com/document_detail/84781.html?spm=a2c4g.84778.0.0.1dfd70a8oq7Nd3