電子書
如果您需要更詳細的範例
更完整的說明可以取得電子書來學習這個單元
http://glarethink.weebly.com/php2android.html
其他相關章節
請改用新版本的檔案上傳(真心不騙)
HttpClient google在API 22以後被捨棄了, 後來改用HttpUrlConnection
請參考如何跟PHP Server溝通-檔案上傳(HttpUrlConnection)
以下已經棄用
在如何跟PHP Server溝通當中, 我們只進行傳輸文字,
而在如何從網路下載圖片也只是從網路上下載而已,
並沒有說明如何將手機的檔案上傳上去, 因此在這個範例當中,
我們要來示範怎麼將檔案上傳到php server。
主要下載程式碼是從File upload With Apache HttpClient Library來進行改寫的
首先必須去apache下載相關套件(我下載HttpClient 4.2.5這個版本)
http://hc.apache.org/downloads.cgi
建立一個新的專案,
接下來解壓縮以後, 將lib複製到專案中的lib,
接著新增一個檔案, 即是上面網站別人寫好的程式碼,
package com.example.uploadingfiledemo;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class SampleFileUpload {
private static String executeRequest(HttpRequestBase requestBase){
String responseString = "" ;
InputStream responseStream = null ;
HttpClient client = new DefaultHttpClient () ;
try{
HttpResponse response = client.execute(requestBase) ;
if (response != null){
HttpEntity responseEntity = response.getEntity() ;
if (responseEntity != null){
responseStream = responseEntity.getContent() ;
if (responseStream != null){
BufferedReader br = new BufferedReader(new InputStreamReader(responseStream)) ;
String responseLine = br.readLine() ;
String tempResponseString = "" ;
while (responseLine != null){
tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator") ;
responseLine = br.readLine() ;
}
br.close() ;
if (tempResponseString.length() > 0){
responseString = tempResponseString ;
}
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if (responseStream != null){
try {
responseStream.close() ;
} catch (IOException e) {
e.printStackTrace();
}
}
}
client.getConnectionManager().shutdown() ;
return responseString ;
}
public String executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription) {
HttpPost postRequest = new HttpPost (urlString) ;
try{
MultipartEntity multiPartEntity = new MultipartEntity () ;
//The usual form parameters can be added this way
multiPartEntity.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;
FileBody fileBody = new FileBody(file, "application/octect-stream") ;
multiPartEntity.addPart("attachment", fileBody) ;
postRequest.setEntity(multiPartEntity) ;
}catch (UnsupportedEncodingException ex){
ex.printStackTrace() ;
}
return executeRequest (postRequest) ;
}
}
這樣一來我們就可以直接使用他的下載程式,
試著來上傳這張圖片。
但是我們要的是上傳至php server, 因此,
我們必須在php server上面建立一支程式來接收我們的檔案。
<?php
if($_FILES['attachment']['tmp_name']){
move_uploaded_file($_FILES['attachment']['tmp_name'],'images/test.jpg');
echo "Upload files success!";
}
else{
echo "Uploading file failed!";
}
?>
如果寫過php的程式, 你會知道當檔案上傳的時候, 會先將檔案存放在一個暫存資料夾,
因此我們需要將檔案移動到我們php的資料夾之下,
所以我建立了一個images的資料夾來存放上傳的檔案,
而當上傳檔案成功的話, 就將訊息印出來。
接下來可以看到php server上面的資料夾, 出現了我們上傳的檔案。
那我們來看看主畫面的程式是怎麼使用這支上傳程式的,
private String uploadUrl = "http://192.168.1.5/test_upload/uploadfile.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SampleFileUpload fileUpload = new SampleFileUpload () ;
Bitmap bm = BitmapFactory.decodeResource( getResources(), R.drawable.butterfly);
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path,"test.jpg");
try
{
OutputStream outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
}
catch (IOException e){
Log.e("error","file error");
}
String response = fileUpload.executeMultiPartRequest(uploadUrl,
file, file.getName(), "File Upload test jpg description") ;
Toast.makeText(this, response, Toast.LENGTH_SHORT).show();
}
如上面的程式碼顯示,
一開始先將php的位置宣告好,(IP位置會因電腦不同而改變, 請修正為您的IP,
並且設定好檔案資料夾)
我們是將專案內的一個圖檔變成一個File的物件,
再傳入上傳檔案的程式(因為他的參數是吃File),
所以我們傳入以後, 就可以進行檔案上傳,
當上傳結束以後, 會收到來自server的訊息, 檢測是否有上傳成功。