使用SpringBoot集成阿里云OSS服务上传文件

使用SpringBoot集成阿里云OSS服务上传文件

最近想使用阿里云的OSS服务,由于阿里云官方文档不是那么简洁,所以记录一下如何使用

第一步,引入相关的依赖


        <dependency>
            <groupId>com.aliyun.oss</groupId>
            <artifactId>aliyun-sdk-oss</artifactId>
            <version>2.4.0</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

第二步,在application.properties中写入相应阿里云OSS参数,

#阿里云oss
endpoint=oss-cn-shanghai.aliyuncs.com
accessKeyId=L
accessKeySecret=
bucketName=
fileHost=

第三步,编写一个util类来集成阿里云提供上传服务的类

首先是根据,提供的参数创建连接OSSClient,为了上传文件有不同的访问路径,添加日期和uuid作为路径中的一部分

package com.homyit.ossdemo.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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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 {
    @Value("${endpoint}")
    private String endpoint;
    @Value("${accessKeyId}")
    private String accessKeyId;
    @Value("${bucketName}")
    private String bucketName;
    @Value("${fileHost}")
    private String fileHost;
    @Value("${accessKeySecret}")
    private String accessKeySecret;

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

    /**
     * 上传文件
     */
    public String upLoad(File file) {
        logger.info("------OSS文件上传开始--------" + file.getName());

        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = sd.format(new Date());
        String fileUrl=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);
            }

            // 设置文件路径和名称
            fileUrl = fileHost + "/" + (dateStr + "/" +
                    UUID.randomUUID().toString().replace("-", "") +
                    "-" + file.getName());

            // 上传文件
            PutObjectResult result = client.putObject(new
                    PutObjectRequest(bucketName, fileUrl, file));

            // 设置权限(公开读)
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);

            if (result != null) {
                logger.info("------OSS文件上传成功------" + fileUrl);
            }


        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getErrorMessage());
        } finally {

            if (client != null) {
                client.shutdown();
            }
        }

        return fileUrl;
    }
}

最后编写contrller层

package com.homyit.ossdemo.controller;

import com.homyit.ossdemo.resp.CommonResp;
import com.homyit.ossdemo.util.AliyunOSSUtil;
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;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@RestController
public class UpLoadController {

    @Resource
    private AliyunOSSUtil aliyunOSSUtil;

    /**
     * 文件上传
     */
    @RequestMapping(value = "/uploadFile")
    public CommonResp uploadFile(@RequestParam("file") MultipartFile file) {
        String filename = file.getOriginalFilename();
        File newFile = new File(filename);
        FileOutputStream os = null;
        CommonResp commonResp = new CommonResp();

        try {

            if (file != null &&!( "". equals (filename.trim()) ) ) {

                    os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    file.transferTo(newFile);

                String upLoad = aliyunOSSUtil.upLoad(newFile);// 上传到OSS

                commonResp.setContent("上传路径为: "+upLoad);

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

            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return commonResp;
    }
}

ps:返回给前端的类是Commonresp

package com.homyit.ossdemo.resp;

public class CommonResp<T> {

    /**
     * 业务上的成功或失败
     */
    private boolean success = true;

    /**
     * 返回信息
     */
    private String message;

    /**
     * 返回泛型数据,自定义类型
     */
    private T content;

    public boolean getSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getContent() {
        return content;
    }

    public void setContent(T content) {
        this.content = content;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("ResponseDto{");
        sb.append("success=").append(success);
        sb.append(", message='").append(message).append('\'');
        sb.append(", content=").append(content);
        sb.append('}');
        return sb.toString();
    }
}

在postman中测试得到

postman

在浏览器中打开得到

效果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值