springboot上传文件到阿里云OSS

第一步,在application.yml做一下配置,预设下载目录

files:
  upload:
    path: D:/SpringBootItem/springboot/files/

其中有用到hutool工具依赖,如下在pom.xml中添加依赖,也可以选择不添加,自己修改下Controller中的代码即可

        <!-- hutool工具包 -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.20</version>
        </dependency>

第二步,新建一个Controller,实现上传到后台服务器指定文件夹。

package com.example.springboot.controller;

/**
* mybatis代码生成器配置
*/
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

import com.example.springboot.service.IUploadLogService;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 上传文件
 */
@RestController
@RequestMapping("/file")
public class UploadLogController {

    /**
     * 上传到本地磁盘地址【从application.yml中获取预设置地址参数】
     */
    @Value("${files.upload.path}")
    private String fileUploadPath;

    @PostMapping("/upload")
    public String upload (@RequestParam MultipartFile file) throws IOException {

        // 获取文件参数
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        File uploadFiletest = new File(fileUploadPath);

        // 判断是否不存在该目录,如果是,新建一个该目录
        if (!uploadFiletest.exists()) {
            uploadFiletest.mkdirs();
        }

        // 定义一个文件的唯一标识码
        String uuid = IdUtil.fastSimpleUUID();

        // 重新拼接
        File uploadFile = new File(fileUploadPath + uuid + "." + type);

        // 进行存储到磁盘
        file.transferTo(uploadFile);

        return "1";
    }

}

效果

 

第三步、配置阿里云oss的依赖

        <!-- 阿里云OSS -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.15.1</version>
        </dependency>

第四步、写一个阿里云OSS处理的工具类(核心),配置相应的阿里云oss账号信息,如何设置阿里云OSS账号及获取账号信息,可以去阿里云官方文档查看,如下:

如何使用STS以及签名URL临时授权访问OSS资源(Java)_对象存储 OSS-阿里云帮助中心 (aliyun.com)

package com.example.springboot.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Value;

import java.io.ByteArrayInputStream;

/**
 * 阿里云OSS工具类
 */
public class AliOssUtil {

    // endpoint填写Bucket所在地域。以华东1(杭州)为例,Region填写为oss-cn-hangzhou.aliyuncs.com。
    public static final String endpoint = "oss-cn-hangzhou.aliyuncs.com";
    // 阿里云账号RAM用户进行API访问或日常运维(账号)。
    public static final String accessKeyId = "************************";
    // 阿里云账号RAM用户进行API访问或日常运维(密钥)。
    public static final String accessKeySecret = "***************************";
    // bucket名
    public static String bucket = "bucketName";


    // 连接阿里云OSS
    public static OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    /**
     * 阿里云OSS上传文件
     * @param data
     * @param url
     * @return
     */
    public static String uploadFile(byte[] data, String url) {
        try{
            ossClient.putObject(bucket, url, new ByteArrayInputStream(data));
            return "true";
        } catch (Exception e) {
            System.out.println(e);
            return "false";
        }
    }

    /**
     * 阿里云OSS删除文件
     * @param url
     * @return
     */
    public static String delFile(String url) {
        try{
            ossClient.deleteObject(bucket, url);
            return "true";
        } catch (Exception e) {
            System.out.println(e);
            return "false";
        }
    }
}

第五步、重新回到第二步的controller接口类进行引用oss工具类的上传和删除方法即可。

package com.example.springboot.controller;

/**
* mybatis代码生成器配置
*/
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.entity.UploadLog;
import com.example.springboot.utils.AliOssUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

import com.example.springboot.service.IUploadLogService;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 上传日志 前端控制器
 * </p>
 *
 * @author Sca_jie
 * @since 2023-09-13
 */
@RestController
@RequestMapping("/file")
public class UploadLogController {

    /**
    * 自定义controller生成模板
    */
    @Resource
    private IUploadLogService uploadLogService;

    /**
     * 上传到本地磁盘地址【从application.yml中获取预设置地址参数】
     */
    @Value("${files.upload.path}")
    private String fileUploadPath;


    /**
     * 上传文件
     * @param file 文件(form-data类型,参数名file)
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload (@RequestParam MultipartFile file) throws IOException {

        // 获取文件参数
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();

        File uploadFiletest = new File(fileUploadPath);

        // 判断是否不存在该目录,如果是,新建一个该目录
        if (!uploadFiletest.exists()) {
            uploadFiletest.mkdirs();
        }

        // 定义一个文件的唯一标识码
        String uuid = IdUtil.fastSimpleUUID();

        // 重新拼接
        File uploadFile = new File(fileUploadPath + uuid + "." + type);

        // 进行存储到磁盘
        file.transferTo(uploadFile);

        // 读取文件
        FileInputStream fileInputStream = new FileInputStream(fileUploadPath + uuid + "." + type);
        byte[] data = IOUtils.readStreamAsByteArray(fileInputStream);

        // 上传阿里云OSS
        String res = AliOssUtil.uploadFile(data, "upload/2023-09/" + uuid + "." + type);

        return res;
    }

    /**
     * 删除阿里云OSS文件
     * @param url
     * @return
     */
    @PostMapping("/delfile")
    public String delFile (@RequestParam String url) {
        System.out.println(url);
        String res = AliOssUtil.delFile(url);
        return res;
    }

}

 效果如下:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值