SpringBoot整合阿里OSS

 功能测试版一共需要这几个文件

 必要的jar包,和非必要的jar包

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

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

yml配置

ali:
  access-key: xxxxxxxxxxxxxxxxx
  access-key-secret: xxxxxxxxxxxx
  bucket-name: xxxxxx
  endpoint: oss-cn-hangzhou.aliyuncs.com

拼接文件名的工具类 FileUtil.java

import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

public class FileUtil {

    public static String concatAllPath(String... pathList) {
        StringBuilder path = new StringBuilder();
        for (int i = 0; i < pathList.length; i++) {
            if (i != 0) {
                path.append("/").append(pathList[i]);
            } else {
                path.append(pathList[i]);
            }
        }
        return path.toString();
    }

    // 获取文件后缀名
    public static String createUuIdName(MultipartFile file) {
        String saveFileName = file.getOriginalFilename();
        // 获取后缀名
        String[] strArray = saveFileName.split("\\.");
        int suffixIndex = strArray.length - 1;
        String exe = strArray[suffixIndex];
        return UUID.randomUUID().toString().replaceAll("-", "") + "." + exe;
    }
}

OSS上传时使用的工具类 OssConfigurationProperties.java

import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;

@Data
@Component
@ConfigurationProperties(prefix = "ali")
public class OssConfigurationProperties {

    // bucket
    private String bucketName;

    // 域名 oss-cn-chengdu.aliyuncs.com
    private String endpoint;

    // accessKeyId
    private String accessKey;

    // accessKeySecret
    private String accessKeySecret;


    // 文件上传
    public boolean upload(String filePath, String url) {
        OSSClient client = new OSSClient(endpoint, accessKey, accessKeySecret);
        try {
            // 上传文件流。
            InputStream inputStream = new FileInputStream(filePath);
            client.putObject(bucketName, url, inputStream);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            // 关闭OSSClient。
            client.shutdown();
        }
    }
    // 重载upload
    public boolean upload(InputStream is, String url) {
        OSSClient client = new OSSClient(endpoint, accessKey, accessKeySecret);
        try {
            // 上传文件流。
            client.putObject(bucketName, url, is);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            // 关闭OSSClient。
            client.shutdown();
        }
    }


    // 删除文件
    public boolean delFile(String path) {
        OSSClient client = new OSSClient(endpoint, accessKey, accessKeySecret);
        String[] split = path.split("/");
        String[] newPath = Arrays.copyOfRange(split, 3, split.length);
        StringBuilder ossPath = new StringBuilder();
        for (int i = 0; i < newPath.length; i++) {
            if (i == newPath.length - 1)
            {
                ossPath.append(newPath[i]);
            }
            else
            {
                ossPath.append(newPath[i]).append("/");
            }
        }
        try {
            client.deleteObject(bucketName, ossPath.toString());
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            client.shutdown();
        }
    }


    // 获取文件路径
    public String getFileOSSUrl(String url) {
        String prefix = "https://";
        return prefix + bucketName + "." + endpoint + "/" +url;
    }
}

自定义返回的结果集 R.java

import java.util.HashMap;
import java.util.Map;


public class R<T> {

    private Integer code; //编码:1成功,0和其它数字为失败

    private String msg; //错误信息

    private T data; //数据

    private Map map = new HashMap(); //动态数据

    public static <T> R<T> success(T object) {
        R<T> r = new R<T>();
        r.data = object;
        r.code = 1;
        return r;
    }

    public static <T> R<T> error(String msg) {
        R r = new R();
        r.msg = msg;
        r.code = 0;
        return r;
    }

    public R<T> add(String key, Object value) {
        this.map.put(key, value);
        return this;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public Map getMap() {
        return map;
    }

    public void setMap(Map map) {
        this.map = map;
    }
}

测试的controller

import com.example.utils.FileUtil;
import com.example.utils.OssConfigurationProperties;
import com.example.utils.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

@RestController
public class TestController {

    @Resource
    private OssConfigurationProperties configurationProperties;

    @PostMapping("/upload")
    public R<String> testUpload(MultipartFile file) throws IOException {
        // 定义存放的文件夹,若没有会在空间中创建一个
        String dir = "menghu";
        // 最终返回可访问的url路径
        String ossURL = "";
        // 拼接加上目录的路径 menghu/12nj1h23b1u3h129hh1.jsp
        String url = FileUtil.concatAllPath(dir, FileUtil.createUuIdName(file));
        // 上传到oss服务器
        boolean upload = configurationProperties.upload(file.getInputStream(), url);
        if (upload) {// 上传oss服务器成功
            // 获取文件访问路径 https://keere-12sdf-23...com/menghu/12nj1h23b1u3h129hh1.jsp
            ossURL = configurationProperties.getFileOSSUrl(url);
        }
        return R.success(ossURL);
    }


}

页面 index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>demo</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<script>
    /**
     * 上传图片
     */
    function uploadImg(){

        /**
         * formData在jquey中使用需要设置:
         * processData: false, // 告诉jQuery不要去处理发送的数据
         * contentType: false // 告诉jQuery不要去设置Content-Type请求头
         * @type {null}
         */
        var fd = new FormData();

        // 第一个参数为controller 接收的参数名称 , input的id
        fd.append("file", document.getElementById("inputId").files[0]);
        $.ajax({
            url:"/upload",
            type:"post",
            data:fd,
            processData:false,
            contentType:false,
            dataType:"json",
            success:function(res){
                console.log(res);
                if (res.code == 1) {
                    $('#imageTest').attr('src', res.data);
                } else {
                    alert("图片上传失败");
                }
            }
        })
    }
</script>

<div id="img">
    <input type="file" name="text" id="inputId">
    <input type="submit" onclick="uploadImg()">
    <!-- 图片链接 -->
    <img src="" id="imageTest" width="1000px">
</div>

</body>
</html>

到这里就可以了

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值