通过OSS上传文件

您在创建签名或模板时,可通过本文档所示方法上传带有链接的登录页面、后台页面截图、软著、协议补充等资料。有助于审核人员了解您的业务详情,提高审核效率。若多个资料可拼接成一个文件,支持png、jpg、jpeg、doc、docx、pdf格式。

步骤一:获取OSS授权信息

通过GetOSSInfoForUploadFile接口获取OSS授权信息。

返回示例:

{
  "RequestId": "A90E4451-FED7-49D2-87C8-00700EDCFD0D",
  "Message": "OK",
  "Model": {
    "Policy": "eyJleHBpcmF0aW9uIjoiMjAyN***Ni0yNVQwNjozNzoyNS45NzBaI**iY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF0sWyJzdGFydHMtd2l0***sIiRrZXkiLCIiXV19",
    "StartPath": "123456",
    "AccessKeyId": "LTAIxetqt1Dg****",
    "Signature": "BXnwCWPrhVb*****aoZHZfli5KE=",
    "Host": "https://alicom-fc-media.oss-cn-zhangjiakou.aliyuncs.com",
    "ExpireTime": "1719297445"
  },
  "Code": "OK",
  "Success": true
}

步骤二:上传文件

说明

调用接口前需配置环境变量,通过环境变量读取访问凭证。AccessKey ID和AccessKey Secret的环境变量名:SMS_ACCESS_KEY_ENV 、SMS_ACCESS_KEY_SECRET_ENV。配置详情请参见配置访问凭证

获取授权信息后,可通过授权信息上传文件到OSS,本文给出服务端上传文件示例。更多详情请参见OSS官网文档在客户端直接上传文件到OSS上传文件到OSS

Java后端上传文件示例

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;


public class HttpOssClient {

    //对应返回值中的Signature
    private String signature = "BXnwCWPrhVb*****aoZHZfli5KE=";
    //对应返回值中的Policy
    private String policy = "eyJleHBpcmF0aW9uIjoiMjAyN***Ni0yNVQwNjozNzoyNS45NzBaI**iY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMTA0ODU3NjAwMF0sWyJzdGFydHMtd2l0***sIiRrZXkiLCIiXV19";
    //本地文件路径
    private String localFilePath = "/Users/Downloads/test.jpg";
    //对应返回值中的AccessKeyId
    private String accessKeyId = "LTAIxetqt1Dg****";
    //对应返回值中的StartPath,注意以 / 结尾
    private String startPath = "123456/";
    //对应返回值中的Host
    private String url = "https://alicom-fc-media.oss-cn-zhangjiakou.aliyuncs.com";


    public static void main(String[] args) throws Exception {
        new HttpOssClient().upload();
    }

    private String getFileName() {
        String fileName = localFilePath;
        if(localFilePath.contains(File.separator)){
            fileName = FilenameUtils.getName(localFilePath);
        }
        String extension = FilenameUtils.getExtension(fileName);
        String prefFileName = StringUtils.substringBefore(fileName,".");
        //文件名进行编码
        String encodeFileName = new String(prefFileName.getBytes(),StandardCharsets.UTF_8);
        //加一个时间戳,防止文件重名覆盖
        fileName = encodeFileName + System.currentTimeMillis() + FilenameUtils.EXTENSION_SEPARATOR + extension ;

        return fileName;
    }

    private void upload() throws Exception {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse httpResponse = null;
        HttpPost httpPost = new HttpPost(url);

        ContentType contentType = ContentType.create("text/plain",StandardCharsets.UTF_8);

        String fileName = getFileName();
        String fileKey = this.startPath + fileName;
        File file = new File(localFilePath);

        HttpEntity requestHttpEntity = MultipartEntityBuilder.create()
                .addTextBody("OSSAccessKeyId", this.accessKeyId)
                .addTextBody("Signature", this.signature)
                .addTextBody("policy", this.policy)
                .setContentType(ContentType.MULTIPART_FORM_DATA)
                .addTextBody("key", fileKey,contentType)
                .addBinaryBody("file", file)
                .setCharset(StandardCharsets.UTF_8)
                .build();

        httpPost.setEntity(requestHttpEntity);

        httpPost.setHeader("User-Agent",
                "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
        httpPost.setHeader("Accept", "*/*");


        httpResponse = httpClient.execute(httpPost);
        HttpEntity entity = httpResponse.getEntity();
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        System.out.println("http status  " + statusCode);

        if (null != entity) {
            String str = EntityUtils.toString(entity);
            System.out.println("http res:  " + str);
        }
        EntityUtils.consume(entity);
        httpClient.close();
        if (httpResponse != null) {
            httpResponse.close();
        }
        if (statusCode >= 200 && statusCode < 300) {
            System.out.println("oss key : " + fileKey);
        } else {
            throw new IOException("Server returned HTTP response code: " + statusCode + " for URL: " + this.url.toString());
        }
    }

}

相关依赖:

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.3</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.0</version>
</dependency>
<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.6</version>
</dependency>

步骤三:设置参数

文件上传成功后,使用示例代码中的fileKey,设置CreateSmsSign、CreateSmsTemplate接口中的MoreData参数值。

MoreData参数填写示例:["123456/test1719383196031.jpg"]