最近有一个需求是要上传音频信息到服务器,为了减少自有服务器的流量,决定使用授权回调上传的形式由客户端直接上传到阿里云oss服务器。
官方文档
https://help.aliyun.com/document_detail/93939.html?spm=a2c4g.11186623.6.1226.6cd07d2dnW4Ekp
中只给出了使用SDK上传的方式,并没有如何自主构建post请求,通过sts服务器拿到的callback信息直接上传。遂从源码中找到请求构建部分,自行构建上传。
java请求构建源码地址:
https://github.com/aliyun/aliyun-oss-java-sdk/blob/master/src/samples/PostObjectSample.java
签名URL服务器返回信息:
下面给出基于源码的修改版代码
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
import javax.activation.MimetypesFileTypeMap;
/**
* Created by shengtao
* on 2020/6/1
*/
/**
* This sample demonstrates how to post object under specfied bucket from Aliyun
* OSS using the OSS SDK for Java.
*/
public class PostObjectSample {
// The local file path to upload.
private static String localFilePath;
public static void postObject(OssInfoBean bean) throws Exception {
String urlStr = bean.getRst().getHost();
// form fields
Map<String, String> formFields = new LinkedHashMap<String, String>();
// key
formFields.put("key", bean.getRst().getKey());
// Content-Disposition
localFilePath = Constant.FileNamePath + bean.getRst().getName();
formFields.put("Content-Disposition", "attachment;filename="
+ localFilePath);
formFields.put("OSSAccessKeyId", bean.getRst().getOSSAccessKeyId());
formFields.put("policy", bean.getRst().getPolicy());
formFields.put("Signature", bean.getRst().getSignature());
formFields.put("callback", bean.getRst().getCallback());
formFields.put("filename", bean.getRst().getName());
String ret = formUpload(urlStr, formFields, localFilePath);
File f = new File(localFilePath);
f.delete();
System.out.println("post reponse formUpload :" + ret);
}
private static String formUpload(String urlStr, Map<String, String> formFields, String localFile)
throws Exception {
String res = "";
HttpURLConnection conn = null;
String boundary = "9431149156168";
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// text
if (formFields != null) {
StringBuffer strBuf = new StringBuffer();
Iterator<Entry<String, String>> iter = formFields.entrySet().iterator();
int i = 0;
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String inputName = entry.getKey();
String inputValue = entry.getValue();
if (inputValue == null) {
continue;
}
if (i == 0) {
strBuf.append("--").append(boundary).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
} else {
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\""
+ inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
i++;
}
out.write(strBuf.toString().getBytes());
}
// file
File file = new File(localFile);
String filename = file.getName();
String contentType = new MimetypesFileTypeMap().getContentType(file);
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(boundary)
.append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"file\"; "
+ "filename=\"" + filename + "\"\r\n");
strBuf.append("Content-Type: " + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
// Gets the file data
strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
res = strBuf.toString();
reader.close();
reader = null;
} catch (Exception e) {
System.err.println("Send post request exception: " + e);
throw e;
} finally {
if (conn != null) {
conn.disconnect();
conn = null;
}
}
return res;
}
}
使用方法:
PostObjectSample.postObject(body);//body为上面截图中的内容
文件地址为:
Constant.FileNamePath + bean.getRst().getName()//自行修改
上传成功后 ,ret信息为:
System.out: post reponse formUpload :{"status": 0, "rst": {"md5sum": "d1f2cedc83c***97116c80e53cf"}, "message": "success", "test_flag": 0, "request_no": "7d****f4-85a6-41ea-9285-9fae58901531"}
至此上传成功。
以上 by:Miyok
网友评论