本文要用java.net.httpurlconnection來實作多個檔案上傳
1. 研究 form 表單到底封裝了什麼樣的資訊發送到servlet。
假如我參數寫的内容是hello word,然後二個檔案是二個簡單的txt檔案,form送出的資訊為:
[xhtml] view
plaincopy
-----------------------------7da2e536604c8
content-disposition: form-data; name="username"
hello word
content-disposition: form-data; name="file1"; filename="d:/haha.txt"
content-type: text/plain
haha
hahaha
content-disposition: form-data; name="file2"; filename="d:/huhu.txt"
messi
huhu
-----------------------------7da2e536604c8--
研究下規律發現有如下幾點特征
1.第一行是“ -----------------------------7d92221b604bc ”作為分隔符,然後是“ /r/n ” 回車換行符。 這個7d92221b604bc 分隔符浏覽器是随機生成的。
2.第二行是content-disposition: form-data; name="file2"; filename="d:/huhu.txt";name=對應input的name值,filename對應要上傳的檔案名(包括路徑在内),
3.第三行如果是檔案就有content-type: text/plain;這裡上傳的是txt檔案是以是text/plain,如果上穿的是jpg圖檔的話就是image/jpg了,可以自己試試看看。
然後就是回車換行符。
4.在下就是檔案或參數的内容或值了。如:hello word。
5.最後一行是-----------------------------7da2e536604c8--,注意最後多了二個--;
有了這些就可以使用httpurlconnection來實作上傳檔案功能了
[java] view
private void upload(string[] uploadfiles, string actionurl) {
string end = "/r/n";
string twohyphens = "--";
string boundary = "*****";
try {
url url = new url(actionurl);
httpurlconnection con = (httpurlconnection) url.openconnection();
// 發送post請求必須設定如下兩行
con.setdoinput(true);
con.setdooutput(true);
con.setusecaches(false);
con.setrequestmethod("post");
con.setrequestproperty("connection", "keep-alive");
con.setrequestproperty("charset", "utf-8");
con.setrequestproperty("content-type",
"multipart/form-data;boundary=" + boundary);
dataoutputstream ds =
new dataoutputstream(con.getoutputstream());
for (int i = 0; i < uploadfiles.length; i++) {
string uploadfile = uploadfiles[i];
string filename = uploadfile.substring(uploadfile.lastindexof("//") + 1);
ds.writebytes(twohyphens + boundary + end);
ds.writebytes("content-disposition: form-data; " +
"name=/"file" + i + "/";filename=/"" +
filename + "/"" + end);
ds.writebytes(end);
fileinputstream fstream = new fileinputstream(uploadfile);
int buffersize = 1024;
byte[] buffer = new byte[buffersize];
int length = -1;
while ((length = fstream.read(buffer)) != -1) {
ds.write(buffer, 0, length);
}
/* close streams */
fstream.close();
}
ds.writebytes(twohyphens + boundary + twohyphens + end);
ds.flush();
// 定義bufferedreader輸入流來讀取url的響應
inputstream is = con.getinputstream();
int ch;
stringbuffer b = new stringbuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
string s = b.tostring();
if (s.contains("successfully")) {
// for (int i = 1; i < 5; i++) {
int beginindex = s.indexof("url =") + 5;
int endindex = s.indexof("/n", beginindex);
string urlstr = s.substring(beginindex, endindex).trim();
system.out.println(urlstr);
// }
ds.close();
} catch (exception e) {
}
}