Post上传对象

ObjectPostSDK接口为一个指定对象生成一个支持post方式上传文件的参数集合,可以在前端使用post form-data的方式上传文件。ObjectPostSDK实现请查看Java SDK Demo

public void postObject() throws Exception {
    String bucketName = Config.BUCKET;
    String objectKey = "ExampleObject.txt";
    String localFilePath = "E:/ExampleObject.txt";

    ObjectPostSDK.PostObjectPolicy policy = new ObjectPostSDK.PostObjectPolicy(900);
    policy.addEqualCondition("acl", "public-read");
    ObjectPostSDK.PostObjectData data = sdk.generatePostObjectData(bucketName, objectKey, policy);
    System.out.println("Policy:" + policy.getPolicy());
    Map<String, String> formFields = data.getFormFields();
    formFields.put("acl", "public-read");
    for (Entry<String, String> entry: formFields.entrySet()){
        System.out.println(entry.getKey() + ":" + entry.getValue());
    }
    String ret = formUpload(data.getUrl(), data.getFormFields(), localFilePath);
    System.out.println("Post Object [" + objectKey + "] to bucket [" + bucketName + "]");
    System.out.println("post response:" + ret);
}

参数如下:

参数 类型 说明 是否必要
Bucket 字符串 bucket的名称
Key 字符串 对象的key
Expires 整型数 超时时间(秒) 否,默认900秒

前端使用方式如下:

<form action="<data.url>" method="POST" enctype="multipart/form-data">
    <input type="hidden" name="Policy" value="<data.fields["Policy"]>" />
    <input type="hidden" name="X-Amz-Algorithm" value="<data.fields["X-Amz-Algorithm"]>" />
    <input type="hidden" name="X-Amz-Credential" value="<data.fields["X-Amz-Credential"]>" />
    <input type="hidden" name="X-Amz-Date" value="<data.fields["X-Amz-Date"]>" />
    <input type="hidden" name="X-Amz-Signature" value="<data.fields["X-Amz-Signature"]>" />
    <input type="hidden" name="bucket" value="<data.fields["bucket"]>" />
    <input type="hidden" name="key" value="<data.fields["key"]>" />

    <input type="file" name="file" value="" />
    <input type="submit" value="Submit" />
</form>