Commit a5eb5402 by 王栋源

wdy

parent c5aea15e
package com.example.aliossjava;
import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* @author shiming.zhao
* @date 2019/04/18
*/
public class testuploadossapi {
// 上传文件
private String localFilePath = "F:\\swch\\commons-io-2.6\\aaa.jpg";
// Endpoint以杭州为例,其它Region请按实际情况填写。
private String endpoint = "https://trade-mark-user-upload.oss-cn-beijing.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
private String accessKeyId = "hObpgEXoca42qH3V";
// 存储空间名称
private String bucketName = "trade-mark-user-upload";
// 文件名称
private String objectName = "30039057/icon/1585819302216/tsctdcrevq.jpg";
private String encodePolicy = "eyJleHBpcmF0aW9uIjoiMjAyMC0wNC0wMlQwOToyNjo0Mi4yMTZaIiwiY29uZGl0aW9ucyI6W1siY29udGVudC1sZW5ndGgtcmFuZ2UiLDAsMjA0ODAwXSxbInN0YXJ0cy13aXRoIiwiJGtleSIsIjMwMDM5MDU3L2ljb24vMTU4NTgxOTMwMjIxNiJdLFsiZXEiLCIkYnVja2V0IiwidHJhZGUtbWFyay11c2VyLXVwbG9hZCJdXX0=";
private String signature = "sjwOVn0B+Dt5JzcGPLYxccE3aEk=";
public void doUpload() throws Exception {
// 在URL中添加存储空间名称,添加后URL如下:http://yourBucketName.oss-cn-hangzhou.aliyuncs.com
String urlStr = endpoint.replace("http://", "http://" + bucketName + ".");
// 表单Map。
Map<String, String> formFields = new LinkedHashMap<String, String>();
// 设置文件名称。
formFields.put("key", this.objectName);
// 设置Content-Disposition。
formFields.put("Content-Disposition", "attachment;filename="
+ localFilePath);
// 设置OSSAccessKeyId。
formFields.put("OSSAccessKeyId", accessKeyId);
// 设置policy。
formFields.put("policy", encodePolicy);
// 生成签名。
//String signaturecom = com.aliyun.oss.common.auth.ServiceSignature.create().computeSignature(accessKeySecret,
// encodePolicy);
// 设置签名。
formFields.put("Signature", signature);
String ret = formUpload(urlStr, formFields, localFilePath);
System.out.println("Post Object [" + this.objectName + "] to bucket [" + bucketName + "]");
System.out.println("post reponse:" + 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)");
// 设置MD5值。MD5值是由整个body计算得出的。
//conn.setRequestProperty("Content-MD5", "<yourContentMD5>");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
OutputStream out = new DataOutputStream(conn.getOutputStream());
// 遍历读取表单Map中的数据,将数据写入到输出流中。
if (formFields != null) {
StringBuffer strBuf = new StringBuffer();
Iterator<Map.Entry<String, String>> iter = formFields.entrySet().iterator();
int i = 0;
while (iter.hasNext()) {
Map.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 = 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();
// 读取返回数据。
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;
}
}
......@@ -41,7 +41,10 @@ public class uploadossapi {
public void helloworlds(){
try {
System.out.println("fdfd");
testuploadossapi testuploadossapi=new testuploadossapi();
testuploadossapi.doUpload();
} catch (Exception e) {
System.err.println("Send post request exception: " + e);
}
}
}
......@@ -19,27 +19,24 @@ public class utilupload {
// 上传文件
private String localFilePath = "";
// Endpoint以杭州为例,其它Region请按实际情况填写。
private String endpoint = "";
private String endpoint = "http://oss-cn-beijing.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维,请登录 https://ram.console.aliyun.com 创建RAM账号。
private String accessKeyId = "";
private String accessKeyId = "hObpgEXoca42qH3V";
// 存储空间名称
private String bucketName = "";
private String bucketName = "trade-mark-user-upload";
// 文件名称
private String objectName = "";
private String encodePolicy = "";
private String signature = "";
public void doUpload(String ossurl,String endpoint,String accessKeyId,String bucketName,String objectName,String encodePolicy,String signature) throws Exception {
public void doUpload(String ossurl,String endpoint1,String accessKeyId1,String bucketName1,String objectName,String encodePolicy,String signature) throws Exception {
URL httpurl = new URL(ossurl);
File file = new File("F:\\swch\\commons-io-2.6\\aaa.jpg");
FileUtils.copyURLToFile(httpurl, file);
this.objectName=objectName;
this.endpoint=endpoint;
this.accessKeyId=accessKeyId;
this.bucketName=bucketName;
this.objectName="30039057/icon/1585794705963/"+objectName;
// this.endpoint=endpoint;
// this.accessKeyId=accessKeyId;
// this.bucketName=bucketName;
this.localFilePath="F:\\swch\\commons-io-2.6\\aaa.jpg";
// 在URL中添加存储空间名称,添加后URL如下:http://yourBucketName.oss-cn-hangzhou.aliyuncs.com
String urlStr = endpoint.replace("http://", "http://" + bucketName + ".");
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment