上傳檔案實現方法

來源:互聯網
上載者:User

標籤:request   win   ack   map   with   請求   continue   int   finally   

public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap, String uri) {
String res = "";
HttpURLConnection conn = null;
String BOUNDARY = "---------------------------123821742118716"; // boundary就是request頭和上傳檔案內容的分隔字元
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
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 (textMap != null) {
StringBuilder strBuilder = new StringBuilder();
for (Object o : textMap.entrySet()) {
Map.Entry entry = (Map.Entry) o;
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}
strBuilder.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuilder.append("Content-Disposition: form-data; name=\"").append(inputName).append("\"\r\n\r\n");
strBuilder.append(inputValue);
}
out.write(strBuilder.toString().getBytes());
}

// file
if (fileMap != null) {
for (Object o : fileMap.entrySet()) {
Map.Entry entry = (Map.Entry) o;
String inputName = (String) entry.getKey();
String inputValue = (String) entry.getValue();
if (inputValue == null) {
continue;
}

InputStream inputStream = new URL(uri).openStream();
File file = new File(inputValue);
String filename = file.getName();
String contentType = new MimetypesFileTypeMap().getContentType(file);
if (filename.endsWith(".png")) {
contentType = "image/png";
}
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}

StringBuilder strBuilder = new StringBuilder();
strBuilder.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
strBuilder.append("Content-Disposition: form-data; name=\"").append(inputName).append("\"; filename=\"").append(filename).append("\"\r\n");
strBuilder.append("Content-Type:").append(contentType).append("\r\n\r\n");

out.write(strBuilder.toString().getBytes());

DataInputStream in = new DataInputStream(inputStream);
int bytes;
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();

// 讀取返回資料
StringBuilder strBuilder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
strBuilder.append(line).append("\n");
}
res = strBuilder.toString();
reader.close();
} catch (Exception e) {
System.out.println("發送POST請求出錯。" + urlStr);
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return res;
}

上傳檔案實現方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.