表单上传(Java SDK V2)

更新时间:
复制 MD 格式

通过 OSS Java SDK V2 按照仓库示例生成 V4 表单签名并通过 HTTP POST 上传文件。

前提条件

  • 已安装 OSS Java SDK V2。使用 Maven 时,请在 pom.xml 中添加依赖 com.aliyun:alibabacloud-oss-v2。

  • 已通过环境变量配置访问凭证。本文示例使用 EnvironmentVariableCredentialsProvider 从环境变量 OSS_ACCESS_KEY_ID 和 OSS_ACCESS_KEY_SECRET 读取凭证。

权限说明

阿里云账号默认拥有全部权限。阿里云账号下的 RAM 用户或 RAM 角色默认没有任何权限,需要阿里云账号或账号管理员授予操作权限。

API

Action

说明

PostObject

oss:PutObject

通过表单方式上传文件到指定 Bucket。

示例代码

import com.aliyun.sdk.service.oss2.credentials.Credentials;
import com.aliyun.sdk.service.oss2.credentials.CredentialsProvider;
import com.aliyun.sdk.service.oss2.credentials.EnvironmentVariableCredentialsProvider;
import com.aliyun.sdk.service.oss2.utils.Base64Utils;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class PostObjectSample {
    public static void main(String[] args) throws Exception {
        String region = "cn-hangzhou";
        String bucket = "examplebucket";
        String key = "exampleobject";
        String localFilePath = "/path/to/local/file";
        String endpoint = "https://" + bucket + ".oss-" + region + ".aliyuncs.com";

        CredentialsProvider provider = new EnvironmentVariableCredentialsProvider();
        Credentials credentials = provider.getCredentials();
        String accessKeyId = credentials.accessKeyId();
        String accessKeySecret = credentials.accessKeySecret();

        String date = Instant.now().atOffset(ZoneOffset.UTC)
                .format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String dateTime = Instant.now().atOffset(ZoneOffset.UTC)
                .format(DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        String credential = accessKeyId + "/" + date + "/" + region + "/oss/aliyun_v4_request";

        Map<String, Object> policyMap = new LinkedHashMap<>();
        policyMap.put("expiration", "2120-01-01T12:00:00.000Z");
        List<Object> conditions = new ArrayList<>();
        conditions.add(Collections.singletonMap("bucket", bucket));
        conditions.add(Collections.singletonMap("x-oss-signature-version", "OSS4-HMAC-SHA256"));
        conditions.add(Collections.singletonMap("x-oss-credential", credential));
        conditions.add(Collections.singletonMap("x-oss-date", dateTime));
        conditions.add(Arrays.asList("content-length-range", 0, 104857600));
        policyMap.put("conditions", conditions);

        String policy = new ObjectMapper().writeValueAsString(policyMap);
        String encodedPolicy = Base64Utils.encodeToString(policy.getBytes(StandardCharsets.UTF_8));

        Map<String, String> formFields = new LinkedHashMap<>();
        formFields.put("key", key);
        formFields.put("policy", encodedPolicy);
        formFields.put("x-oss-signature-version", "OSS4-HMAC-SHA256");
        formFields.put("x-oss-credential", credential);
        formFields.put("x-oss-date", dateTime);
        formFields.put("x-oss-signature",
                calculateSignature(accessKeySecret, date, region, encodedPolicy));

        String response = formUpload(endpoint, formFields, localFilePath);
        System.out.println(response);
    }

    private static String calculateSignature(
            String accessKeySecret, String date, String region, String encodedPolicy) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(
                ("aliyun_v4" + accessKeySecret).getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        byte[] dateKey = mac.doFinal(date.getBytes(StandardCharsets.UTF_8));
        mac.init(new SecretKeySpec(dateKey, "HmacSHA256"));
        byte[] regionKey = mac.doFinal(region.getBytes(StandardCharsets.UTF_8));
        mac.init(new SecretKeySpec(regionKey, "HmacSHA256"));
        byte[] serviceKey = mac.doFinal("oss".getBytes(StandardCharsets.UTF_8));
        mac.init(new SecretKeySpec(serviceKey, "HmacSHA256"));
        byte[] signingKey = mac.doFinal("aliyun_v4_request".getBytes(StandardCharsets.UTF_8));
        mac.init(new SecretKeySpec(signingKey, "HmacSHA256"));
        byte[] signatureBytes = mac.doFinal(encodedPolicy.getBytes(StandardCharsets.UTF_8));

        StringBuilder signature = new StringBuilder();
        for (byte value : signatureBytes) {
            signature.append(String.format("%02x", value & 0xff));
        }
        return signature.toString();
    }

    private static String formUpload(
            String url, Map<String, String> formFields, String localFilePath) throws Exception {
        String boundary = "9431149156168";
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(30000);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (OutputStream output = new DataOutputStream(connection.getOutputStream())) {
            for (Map.Entry<String, String> entry : formFields.entrySet()) {
                output.write(("--" + boundary + "\r\n"
                        + "Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n"
                        + entry.getValue() + "\r\n").getBytes(StandardCharsets.UTF_8));
            }

            File file = new File(localFilePath);
            output.write(("--" + boundary + "\r\n"
                    + "Content-Disposition: form-data; name=\"file\"; filename=\""
                    + file.getName() + "\"\r\n"
                    + "Content-Type: application/octet-stream\r\n\r\n")
                    .getBytes(StandardCharsets.UTF_8));
            try (InputStream input = new FileInputStream(file)) {
                byte[] buffer = new byte[8192];
                int length;
                while ((length = input.read(buffer)) != -1) {
                    output.write(buffer, 0, length);
                }
            }
            output.write(("\r\n--" + boundary + "--\r\n").getBytes(StandardCharsets.UTF_8));
        }

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line).append('\n');
            }
            return response.toString();
        } finally {
            connection.disconnect();
        }
    }
}

相关文档