Android 上傳檔案到伺服器,通常是構造 HTTP 協定、模擬網頁的 POST 方法來傳輸,伺服器端則可用 Java Servlet 或 PHP 接收。以 Servlet 接收已相當常見,這裡介紹一個用 PHP 接收上傳檔案的簡單範例。
伺服器端程式碼相當直觀,把上傳的暫存檔搬移到目標目錄即可:
<?php
$target_path = "./upload/"; // 接收檔案目錄
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file " . basename( $_FILES['uploadedfile']['name']) . " has been uploaded";
} else {
echo "There was an error uploading the file, please try again!" . $_FILES['uploadedfile']['error'];
}
?>
客戶端以 HttpURLConnection 手工拼接 multipart/form-data 的請求本文,把檔案內容分塊寫入串流:
package com.figo.uploadfile;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class UploadfileActivity extends Activity {
// 要上傳的檔案路徑,理論上可傳輸任何檔案
private String uploadFile = "/sdcard/testimg.jpg";
private String srcPath = "/sdcard/testimg.jpg";
// 伺服器上接收檔案的處理頁面
private String actionUrl = "https://10.100.1.208/receive_file.php";
private TextView mText1;
private TextView mText2;
private Button mButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mText1 = (TextView) findViewById(R.id.myText2);
mText1.setText("檔案路徑:\n" + uploadFile);
mText2 = (TextView) findViewById(R.id.myText3);
mText2.setText("上傳網址:\n" + actionUrl);
mButton = (Button) findViewById(R.id.myButton);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadFile(actionUrl);
}
});
}
/* 上傳檔案至 Server,uploadUrl:接收檔案的處理頁面 */
private void uploadFile(String uploadUrl) {
String end = "\r\n";
String twoHyphens = "--";
String boundary = "******";
try {
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
// 設置每次傳輸的流大小,防止手機因記憶體不足崩潰
httpURLConnection.setChunkedStreamingMode(128 * 1024); // 128K
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
+ srcPath.substring(srcPath.lastIndexOf("/") + 1)
+ "\""
+ end);
dos.writeBytes(end);
FileInputStream fis = new FileInputStream(srcPath);
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(twoHyphens + boundary + twoHyphens + end);
dos.flush();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
Toast.makeText(this, result, Toast.LENGTH_LONG).show();
dos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
setTitle(e.getMessage());
}
}
}
最後別忘了在 AndroidManifest.xml 加上網路存取權限:
<uses-permission android:name="android.permission.INTERNET" />
關鍵在於 setChunkedStreamingMode,它讓上傳以串流方式分塊送出,避免一次把整個檔案讀進記憶體而導致 OOM,這在傳輸較大檔案時尤其重要。