2011-07-18 88 views
4

我需要從Android客戶端上傳文件到URL通過HTTP POST。 如果只上傳1個文件,那對我來說可以。但我的目標URL頁面代碼看起來像下面Android上傳多文件到服務器通過http post

<form action="file_upload.php" enctype ="multipart/form-data" method="post"> 
<input type="file" name="uploadedfile"> 
<input type="file" name="uploadedfile2"> 
<input type="submit"> 
</form> 

如何通過HTTP POST上傳2個文件在同一時間?

+0

謝謝Tibbits〜 – RRTW

回答

3

我嘗試下面的代碼,並確認這是可行的解決辦法:

StringBuffer responseBody=new StringBuffer(); 

Log.i(Constants.TAG, "Ready to upload file..."); 
HttpClient client=new DefaultHttpClient(); 
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); 

Log.i(Constants.TAG, "Set remote URL..."); 
HttpPost post=new HttpPost("http://IP.IP.IP.IP/file_upload.php"); 
MultipartEntity entity=new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 

Log.i(Constants.TAG, "Adding file(s)..."); 
entity.addPart("uploadedfile", new FileBody((FileObj), "application/zip")); 
entity.addPart("uploadedfile2", new FileBody((FileObj), "application/zip")); 

Log.i(Constants.TAG, "Set entity..."); 
post.setEntity(entity); 

BufferedReader bs=null; 
try 
{ 
    Log.i(Constants.TAG, "Upload..."); 
    HttpEntity hEntity=client.execute(post).getEntity(); 
    bs=new BufferedReader(new InputStreamReader(hEntity.getContent())); 
    Log.i(Constants.TAG, "Response length - "+hEntity.getContentLength()); 
    String s=""; 
    while(s!=null) 
    { 
    responseBody.append(s); 
    s=bs.readLine(); 
    Log.i(Constants.TAG, "Response body - "+s); 
    } 
    bs.close(); 
} 
catch(IOException ioe) 
{ 
    Log.i(Constants.TAG, "Error on getting response from Server, "+ioe.toString()); 
    ioe.printStackTrace(); 
    responseBody.append("..."); 
} 

我的平臺是Android 2.2系統,並使用該解決方案需要得到httpmime.jar的項目庫。

+0

如果您需要在請求中添加任何參數,請添加MultiPartEntity對象,如
multiPartEntity.addPart(「testpara」,new StringBody(「value」));
AnkitRox

相關問題