springboot+oss

1.导入依赖

        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.8.3</version>
        </dependency>
         <!--web启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2.配置application.yml

# 到自己的阿里云控制台获取
oss:
 #服务器地址
  endpoint: oss-cn-beijing.aliyuncs.com
  keyId: xxxx
  keysecret: xxxx
  #捅的名称
  bucketname: bucket-crowd-lizhihuan
  #上传路径
  webUrl: https://bucket-crowd-lizhihuan.oss-cn-beijing.aliyuncs.com
  #上传文件要存放的文件夹
  folder: crowd/project/othertest

3.启动类

@SpringBootApplication
public class DbBootSpringBootApplication {

    public static void main(String[] args) {
        SpringApplication.run(DbBootSpringBootApplication.class,args);
    }
}

4.获取application.yml获取的配置项

package com.docin.lzh.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

@Component
@Configuration
public class ConstantConfig {
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.keyId}")
    private String accessKeyId;
    @Value("${oss.keysecret}")
    private String accessKeySecret;
    @Value("${oss.folder}")
    private String folder;
    @Value("${oss.bucketname}")
    private String bucketName;
    @Value("${oss.webUrl}")
    private String webUrl;

    public String getEndpoint() {
        return endpoint;
    }

    public void setEndpoint(String endpoint) {
        this.endpoint = endpoint;
    }

    public String getAccessKeyId() {
        return accessKeyId;
    }

    public void setAccessKeyId(String accessKeyId) {
        this.accessKeyId = accessKeyId;
    }

    public String getAccessKeySecret() {
        return accessKeySecret;
    }

    public void setAccessKeySecret(String accessKeySecret) {
        this.accessKeySecret = accessKeySecret;
    }

    public String getFolder() {
        return folder;
    }

    public void setFolder(String folder) {
        this.folder = folder;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public String getWebUrl() {
        return webUrl;
    }

    public void setWebUrl(String webUrl) {
        this.webUrl = webUrl;
    }
}

5.封装一个实体类

package com.docin.lzh.pojo;

import java.io.Serializable;

public class FileDTO implements Serializable {

    /**
     * 文件大小
     */
    private Long fileSize;
    /**
     * 文件的绝对路径
     */
    private String fileAPUrl;

    /**
     * 文件的web访问地址
     */
    private String webUrl;

    /**
     * 文件后缀
     */
    private String fileSuffix;
    /**
     * 存储的bucket
     */
    private String fileBucket;

    /**
     * 原文件名
     */
    private String oldFileName;
    /**
     * 存储的文件夹
     */
    private String folder;

    public FileDTO() {
    }

    public FileDTO(Long fileSize, String fileAPUrl, String webUrl, String fileSuffix, String fileBucket, String oldFileName, String folder) {
        this.fileSize = fileSize;
        this.fileAPUrl = fileAPUrl;
        this.webUrl = webUrl;
        this.fileSuffix = fileSuffix;
        this.fileBucket = fileBucket;
        this.oldFileName = oldFileName;
        this.folder = folder;
    }

    public Long getFileSize() {
        return fileSize;
    }

    public void setFileSize(Long fileSize) {
        this.fileSize = fileSize;
    }

    public String getFileAPUrl() {
        return fileAPUrl;
    }

    public void setFileAPUrl(String fileAPUrl) {
        this.fileAPUrl = fileAPUrl;
    }

    public String getWebUrl() {
        return webUrl;
    }

    public void setWebUrl(String webUrl) {
        this.webUrl = webUrl;
    }

    public String getFileSuffix() {
        return fileSuffix;
    }

    public void setFileSuffix(String fileSuffix) {
        this.fileSuffix = fileSuffix;
    }

    public String getFileBucket() {
        return fileBucket;
    }

    public void setFileBucket(String fileBucket) {
        this.fileBucket = fileBucket;
    }

    public String getOldFileName() {
        return oldFileName;
    }

    public void setOldFileName(String oldFileName) {
        this.oldFileName = oldFileName;
    }

    public String getFolder() {
        return folder;
    }

    public void setFolder(String folder) {
        this.folder = folder;
    }
}

6.封装上传阿里云工具类

package com.docin.lzh.util;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.docin.lzh.pojo.FileDTO;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class AliyunOSSUtil {

    private static Logger logger = Logger.getLogger(AliyunOSSUtil.class);

    @Autowired
    private ConstantConfig constantConfig;

    /**
     * 上传文件
     */
    public FileDTO upLoad(File file) {
        logger.info("------OSS文件上传开始--------" + file.getName());
        String endpoint = constantConfig.getEndpoint();
        System.out.println("获取到的Point为:" + endpoint);
        String accessKeyId = constantConfig.getAccessKeyId();
        String accessKeySecret = constantConfig.getAccessKeySecret();
        String bucketName = constantConfig.getBucketName();
        String fileHost = constantConfig.getFolder();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = format.format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String suffix = file.getName().substring(file.getName().lastIndexOf(".") + 1);
        // 判断文件
        if (file == null) {
            return null;
        }
        OSSClient client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 判断容器是否存在,不存在就创建
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                client.createBucket(createBucketRequest);
            }
            // 设置文件路径和名称
            String fileUrl = fileHost + "/" + (dateStr + "/" + uuid) + "-" + file.getName();
            // 设置权限(公开读)
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            // 上传文件
            PutObjectResult result = client.putObject(new PutObjectRequest(bucketName, fileUrl, file));

            if (result != null) {
                System.out.println(result);
                logger.info("------OSS文件上传成功------" + fileUrl);
                return new FileDTO(
                        file.length(),//文件大小
                        fileUrl,//文件的绝对路径
                        constantConfig.getWebUrl() + "/" + fileUrl,//文件的web访问地址
                        suffix,//文件后缀
                        "",//存储的bucket
                        bucketName,//原文件名
                        fileHost//存储的文件夹
                );

            }
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
        } finally {
            if (client != null) {
                client.shutdown();
            }
        }
        return null;
    }
}

7.编写controller

 /** 文件上传*/
    @RequestMapping(value = "/uploadFile")
    @ResponseBody
    public FileDTO uploadBlog(@RequestParam("file") MultipartFile file) {
        logger.info("文件上传");
        String filename = file.getOriginalFilename();
        System.out.println("要上传的文件名称:" + filename);

        try {
            // 判断文件
            if (file!=null) {
                if (!"".equals(filename.trim())) {
                    File newFile = new File(filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    // 上传到OSS
                    return aliyunOSSUtil.upLoad(newFile);
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

8.使用postman测试

{
    "fileSize": 22667,
    "fileAPUrl": "crowd/project/othertest/2021-04-25/ef316b6bade3424e8eecaf8e5588df4a-256144534.jpg",
    "webUrl": "https://bucket-crowd-lizhihuan.oss-cn-beijing.aliyuncs.com/crowd/project/othertest/2021-04-25/ef316b6bade3424e8eecaf8e5588df4a-256144534.jpg",
    "fileSuffix": "jpg",
    "fileBucket": "",
    "oldFileName": "bucket-crowd-lizhihuan",
    "folder": "crowd/project/othertest"
}
SpringBoot可以通过阿里云的OSS(Object Storage Service)实现文件上传,以下是实现步骤: 1. 引入阿里云OSS SDK依赖 在pom.xml中引入以下依赖: ```xml <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency> ``` 2. 配置OSS连接信息 在application.properties文件中配置OSS连接信息: ```properties oss.endpoint=your-endpoint oss.accessKeyId=your-access-key-id oss.accessKeySecret=your-access-key-secret oss.bucketName=your-bucket-name ``` 3. 创建OSS客户端 在配置类中创建OSS客户端: ```java @Configuration public class OSSConfiguration { @Value("${oss.endpoint}") private String endpoint; @Value("${oss.accessKeyId}") private String accessKeyId; @Value("${oss.accessKeySecret}") private String accessKeySecret; @Bean public OSSClient ossClient() { return new OSSClient(endpoint, accessKeyId, accessKeySecret); } } ``` 4. 实现上传接口 ```java @RestController public class UploadController { @Autowired private OSSClient ossClient; @Value("${oss.bucketName}") private String bucketName; @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { String fileName = file.getOriginalFilename(); try { ossClient.putObject(bucketName, fileName, new ByteArrayInputStream(file.getBytes())); return "success"; } catch (IOException e) { e.printStackTrace(); } finally { ossClient.shutdown(); } return "fail"; } } ``` 以上就是通过阿里云OSS实现文件上传的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值