自学内容网 自学内容网

spring boot 文件上传

文件上传,在开发中是再正常不过的功能了。不管是哪个语言,不管你在开发啥功能,都会遇上。那么,在实际的开发中,文件上传分两种,一种是上传到oss服务器,另一种是上传到本地服务器。
阿里oss云服务器
1、导入坐标依赖

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

2、配置oss,根据自己的服务来写,配置文件名为【application.yml】

aliyun:
  oss:
    endpoint: *********
    accessKeyId: *********
    accessKeySecret: *********
    bucketName: *********
    WebPath: *********

3、建立 FileOssService 接口

package com.bnc.s12.service;


import org.springframework.web.multipart.MultipartFile;

public interface FileOssService {
    String upLoadOss(MultipartFile file);
}

package com.bnc.s12.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.bnc.s12.common.OSSConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
@Slf4j
public class FileOssServiceImpl implements FileOssService {
    @Autowired
    private OSSConfig ossConfig;


    @Override
    public String upLoadOss(MultipartFile file) {
        String bucketName = ossConfig.getBucketName();
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();



        OSS ossClient = new OSSClientBuilder().build(endpoint , accessKeyId , accessKeySecret);
        String originalFilename = file.getOriginalFilename();

        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(extension);

//这儿必须得用try---catch 不然会报错的
        try {
            PutObjectResult path = ossClient.putObject(bucketName , originalFilename , file.getInputStream());

            String p = "https://" + bucketName + "." + endpoint + "/" + originalFilename;
            System.out.println(p);

        }catch (Exception e) {
            //e.printStackTrace();
        }



        return "";
    }
}

4、在控制器中的代码如下

@PostMapping("/myUploadOss")
//file 为前端 file 的 name 属性名
 public String myUploadOss(@RequestPart("file") MultipartFile file){
      String s = fileOssService.upLoadOss(file);
      return "success";
  }

原文地址:https://blog.csdn.net/weixin_42371812/article/details/143785053

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!