com.aliyun.uploader.SaeUploader Maven / Gradle / Ivy
package com.aliyun.uploader;
import com.aliyun.Context;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.http.MethodType;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.http.Consts;
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.HttpEntityWrapper;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class SaeUploader implements Uploader {
private static final Gson GSON = new GsonBuilder().create();
private String packageVersion;
private String regionId;
private String appId;
public SaeUploader(String regionId, String appId, String packageVersion) {
this.packageVersion = packageVersion;
this.regionId = regionId;
this.appId = appId;
}
@Override public String getName() {
return "Sae uploader";
}
@Override public String upload(File fileName) throws Exception {
SaeUploadSignatureModel signature = getUploadSignature(appId, regionId, fileName.getName(), packageVersion);
doUpload(signature, fileName);
//TODO sae url链接是外网的?
return getDownloadUrl(signature);
}
private String getDownloadUrl(SaeUploadSignatureModel signature) {
String url = signature.getData().getUrl();
String key = signature.getData().getKey();
return url + "/" + key;
}
public SaeUploadSignatureModel getUploadSignature(String appId,
String regionId, String fileName, String packageVersion) throws ClientException {
CommonRequest request = new CommonRequest();
request.setMethod(MethodType.POST);
request.setDomain("sae." + regionId + ".aliyuncs.com");
request.setVersion("2019-05-06");
request.setUriPattern("/pop/v1/sam/oss/assignUploadSignature");
request.putQueryParameter("RegionId", regionId); // 注意,这里是物理 RegionId
// 这里必须使用时间戳
String pv = Long.toString(System.currentTimeMillis());
request.putQueryParameter("PackageVersion", pv);
request.putQueryParameter("FileName", fileName);
System.out.print("appId:"+appId);
request.putQueryParameter("AppId", appId);
request.putHeadParameter("Content-Type", "application/json");
String requestBody = "";
request.setHttpContent(requestBody.getBytes(), "utf-8", FormatType.JSON);
CommonResponse response = null;
DefaultAcsClient client = Context.getAcsClient();
response = client.getCommonResponse(request);
return GSON.fromJson(response.getData(), SaeUploadSignatureModel.class);
}
protected void doUpload(SaeUploadSignatureModel signature, File file) throws Exception {
ContentType contentText = ContentType.create("text/plain", Consts.UTF_8);
FileInputStream fis = new FileInputStream(file);
long fileBytes = fis.getChannel().size();
HttpEntity form = MultipartEntityBuilder.create()
.addTextBody("success_action_status", "200")
.addTextBody("bucketName", signature.getData().getBucketName())
.addTextBody("key", signature.getData().getKey(), contentText)
.addTextBody("policy", signature.getData().getPolicy())
.addTextBody("Signature", signature.getData().getSignature())
.addTextBody("OSSAccessKeyId", signature.getData().getOSSAccessKeyId())
.addBinaryBody("file", fis,
ContentType.APPLICATION_OCTET_STREAM, file.getName())
.build();
ProgressListener pListener = new ProgressListener() {
@Override public void progress(float percentage) {
System.out.print("\r");
String bar = "";
for (int i = 0; i < 50; i++) {
bar += i * 2 < percentage ? "#" : ".";
}
System.out.print("[INFO] [" + bar + "] " + percentage + "%");
}
};
HttpPost post = new HttpPost(signature.getData().getUrl());
post.setEntity(new ProgressEntityWrapper(form, pListener, fileBytes));
post.setHeader("Access-Control-Allow-Origin", "*");
CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(post);
}
public interface ProgressListener {
void progress(float percentage);
}
public class ProgressEntityWrapper extends HttpEntityWrapper {
private ProgressListener listener;
private long fileBytes;
public ProgressEntityWrapper(HttpEntity entity, ProgressListener listener, long fileBytes) {
super(entity);
this.listener = listener;
this.fileBytes = fileBytes;
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
super.writeTo(new CountingOutputStream(outstream, listener, fileBytes));
}
}
public static class CountingOutputStream extends FilterOutputStream {
private ProgressListener listener;
private long transferred;
private long totalBytes;
public CountingOutputStream(
OutputStream out, ProgressListener listener, long totalBytes) {
super(out);
this.listener = listener;
transferred = 0;
this.totalBytes = totalBytes;
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
transferred += len;
listener.progress(getCurrentProgress());
}
@Override
public void write(int b) throws IOException {
out.write(b);
transferred++;
listener.progress(getCurrentProgress());
}
private float getCurrentProgress() {
return Math.round(((float) transferred / totalBytes) * 10000)/100;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy