OSS文件上传

1.添加相关依赖

   
        
            com.alibaba.cloud
            aliyun-oss-spring-boot-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            2.2.10.RELEASE
        

2.yml配置

#对应的配置文件
alibaba:
  cloud:
    secret-key: 
    access-key: 
    oss:
      endpoint: oss-cn-beijing.aliyuncs.com
      bucket: 
server:
  port: 8091

3.

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.qf.java2201.common.R;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @date 2022/6/5
 * @desc
 */
@RestController
@Api(tags = "阿里云存储服务返回签名策略的方式")
@RequestMapping("/thirdservice/ossservice")
public class OssPolicyController {
    @Resource
    OSS ossClient;

    @Value("${alibaba.cloud.oss.endpoint}")
    private String endpoint;
    @Value("${alibaba.cloud.oss.bucket}")
    private String bucket;

    @Value("${alibaba.cloud.access-key}")
    private String accessId;


    @PostMapping("/uploadPolicy")
    public R policy() {



        //https://glsc-glls.oss-cn-beijing.aliyuncs.com/hahaha.jpg

        String host = "https://" + bucket + "." + endpoint; // host的格式为 bucketname.endpoint
        // callbackUrl为 上传回调服务器的URL,请将下面的IP和Port配置为您自己的真实信息。
//        String callbackUrl = "http://88.88.88.88:8888";
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format + "/"; // 用户上传文件时指定的前缀。

        Map respMap = null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));


            // 下面是 回调  和 以跨域的方式响应数据  咱们配置过跨域了 所以这里注释掉
         /*   JSONObject jasonCallback = new JSONObject();
            jasonCallback.put("callbackUrl", callbackUrl);
            jasonCallback.put("callbackBody",
                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            respMap.put("callback", base64CallbackBody);

            JSONObject ja1 = JSONObject.fromObject(respMap);
            // System.out.println(ja1.toString());
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST");
            response(request, response, ja1.toString());*/


        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        }
        return R.ok().data("data",respMap);
        //return R.ok().put("data",respMap);
    }
}
package com.qf.java2201.edu.ossservice.controller;

import com.aliyun.oss.OSS;
import com.qf.java2201.common.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @date 2022/5/28
 * @desc
 */
@RestController
@Api(tags = "阿里云存储服务通过服务器直传的方式")
@RequestMapping("/ossservice")
public class OssController {

    @Resource
    private OSS ossClient;


    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public R uploadPic(MultipartFile file) throws IOException {
        // 上传照片

        String filename = file.getOriginalFilename();  // 得到文件的名字

        InputStream inputStream = file.getInputStream();  // 将file 对象转为 输入流

        String objectName =   System.currentTimeMillis() +  filename.substring(filename.lastIndexOf("."));
        String dir = "img";

        // 阿里云存储  返回 上传之后的文件路径
        ossClient.putObject("qf2201",  dir+"/"+objectName, inputStream);

// 关闭OSSClient。
        ossClient.shutdown();
        String filePath = "https://qf2201.oss-cn-beijing.aliyuncs.com/img/"+objectName;

        return R.ok().data("url",filePath);
    }

}

你可能感兴趣的:(java)