Android Http上傳文件 PHP接收

Client

創建HttpURLConnection,並設置屬性(相當於請求頭),其中最後一句最重要,multipart/form-data定義了是“文件上傳”,boundary=*定義了分割線(人造POST格式要求非常嚴格!!)

URL url = new URL(uploadUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setChunkedStreamingMode(128 * 1024);
hconnection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Charset", "UTF-8");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=*******");

然後是請求體,一定要注意格式!!

- -boundry //表示開始(兩個橫線中間空格去掉!!)
Content-Disposition: form-data; name=\”file\”; filename=\”asd.jpg\”” //name要跟PHP中$_FILES[‘??’]一樣!!filename會賦值給PHP中的$_FILES[‘??’][‘name’]

file的字節¥#……¥%&……%&%&%&

- -boundry- - //表示結束(兩個橫線中間空格去掉!!)

DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
dos.writeBytes("--" + "*******" + end);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"asd.jpg\"" + end);
dos.writeBytes(end);

FileInputStream fis = new FileInputStream(path);
byte[] buffer = new byte[8192]; // 8k
int count = 0;
while ((count = fis.read(buffer)) != -1) {
     dos.write(buffer, 0, count);
}
fis.close();
dos.writeBytes(end);
dos.writeBytes("--" + "*******" + "--" + end);
dos.flush();

最後接收響應結果

InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = "";
String line;
while ((line = br.readLine()) != null){
      result += line;
}
System.out.println(result);
dos.close();
is.close();

Servlet

只要設置了multipart/form-data,上傳文件會被自動接收到一個臨時文件夾,腳本結束時自動刪除,所有的相關屬性可以通過$_FILES讀到。想永久保存,要用move_uploaded_file()函數,第一個參數是$_FILES [‘file’] [‘tmp_name’],第二個參數是$_FILES [‘file’] [‘name’](這個可以變,一般用這個,Servlet文件名和Client保持一致,前面還可以加個文件夾比如”./uploads/”,但是必須提前新建它)。
$_FILES[‘file’][‘error’]用於輸出錯誤。
$_FILES[“userfile”][“size”]上傳文件的大小。
$_FILES[“userfile”][“type”]上傳文件的類型,用於驗證類型。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章