文件上传Oss——前、后端结合(基于Springboot)(小白笔记)

文件上传Oss——前、后端结合(基于Springboot)

兄弟篇:

文件上传Oss——纯前端(1)(小白笔记)

文件上传Oss——纯前端(2)(小白笔记)

所需依赖

<!-- https://mvnrepository.com/artifact/com.aliyun.oss/aliyun-sdk-oss -->
        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>3.9.1</version>
        </dependency>

AliOssUtil工具类

package com.soft1851.music.admin.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author wl_sun
 * @description TODO
 * @Data 2020/5/1
 */
@Slf4j
public class AliOssUtil {
    public static String upload(MultipartFile sourceFile){
        // 获取文件名
        String fileName = sourceFile.getOriginalFilename();
        //uuid生成主文件名
        String prefix = UUID.randomUUID().toString();
        assert fileName != null;
        //源文件的扩展名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //创建File类型的临时文件
        File tempFile = null;
        try {
            tempFile = File.createTempFile(prefix,suffix);
            //将MultipartFile转换成File
            sourceFile.transferTo(tempFile);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        assert tempFile != null;
        return upload(tempFile);
    }
    public static String upload(File file){
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        String accessKeyId = "LT************z6jbo4";
        String accessKeySecret = "6vVUW*********KwVZMjkv";
        String bucketName = "bucket名";
        String filePath = "存储路径,默认根目录";
        String fileName = file.getName();
        String newFileName = UUID.randomUUID().toString() + fileName.substring(fileName.indexOf("."));
        //创建OSSClient实例
//        OSSClient ossClient  = new OSSClient(endpoint,accessKeyId,accessKeySecret);
        OSS ossClient  = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        //上传文件到指定位置,并使用UUID更名
        ossClient.putObject(bucketName,filePath + newFileName,file);
        //拼接URL
        String url = "https://bucket名.oss-cn-beijing.aliyuncs.com/" + filePath + newFileName;
        ossClient.shutdown();
        return url;
    }
    public static void main(String[] args) {
        File file = new File("C:\\Users\\HP\\Desktop\\en\\Python库大全.pdf");
        upload(file);
    }
}

controller类接口编写

package com.soft1851.music.admin.controller;

import com.soft1851.music.admin.annotation.ControllerWebLog;
import com.soft1851.music.admin.common.ResponseResult;
import com.soft1851.music.admin.util.AliOssUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author wl_sun
 * @description TODO
 * @Data 2020/5/1
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class UploadController {

    @PostMapping("/uploadFile")
    @ControllerWebLog
    public ResponseResult uploadSingle(@RequestParam("file") MultipartFile sourceFile) {
        String url = AliOssUtil.upload(sourceFile);
        return ResponseResult.success(url);
    }
}

前端调用接口实现(以上传图片为例)

<input type="file" @change="uploadImage($event)"  id="fileBox" />

uploadImage() {
      let formData = new FormData()
      formData.append('file', event.target.files[0])
      this.axios({
        method: 'post',
        url: this.GLOBAL.baseUrl + '/api/uploadFile',
        headers: {
          'Content-Type': 'multipart/formdata'
        },
        data: formData
      }).then((res) => {
        console.log(res.data.data)
      })
    },

谢谢,欢迎留言交流

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老子裤子马

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值