首先创建一个工具类

package org.example.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.model.PutObjectRequest;

import java.io.File;
import java.io.InputStream;

public class AliOssUtil {

    private static final String ENDPOINT = "区域节点";
    private static final String ACCESS_KEY_ID = "授权KEY_ID";
    private static final String ACCESS_KEY_SECRET = "授权KEY_密钥";
    private static final String BUCKET_NAME = "BUCKET名字";

    /**
     * 上传文件到阿里云OSS
     * @param in 输入流对象
     * @param fileName 上传文件名
     * @return
     */
    public static String upload(InputStream in, String fileName) {
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
        try {
            // 上传文件到OSS。
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, fileName, in);
            ossClient.putObject(putObjectRequest);
            // url组成: https://bucket名称.区域节点/文件名
            String url = "https://" + BUCKET_NAME + "." + ENDPOINT.substring(ENDPOINT.lastIndexOf("/")+1)+"/"+fileName;
            // 返回URL地址
            return url;
        }catch (OSSException e){
            return "上传失败";
        } catch (ClientException ce) {
            return "连接失败";
        }finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
    }
}

然后再通过Controller进行调用该工具类

package org.example.controller;

import org.example.pojo.Result;
import org.example.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file) throws IOException {
        // 将文件的内容存储到本地磁盘上
        String originalFilename = file.getOriginalFilename(); // 获取原始文件名
        // 保证文件的名字是唯一的 - 借助UUID
        String filename = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 本地上传
        //file.transferTo(new File("/Users/luoyufeng/Desktop/temp/" + filename));
        // 阿里云OSS上传
        String url = AliOssUtil.upload(file.getInputStream(),filename);
        return Result.success(url);
    }
}

最后进行测试

结果测试

最后修改:2024 年 01 月 19 日
如果觉得我的文章对你有用,请随意赞赏