2012-04-13 51 views
1

我是java的新手,我必須將文件從Android應用程序傳輸到服務器。我把幫助從鏈接java:使用POST將文件上傳到HTTP服務器,服務器代碼問題?

Uploading files to HTTP server using POST. Android SDK

<?php 
$target_path = "./"; 
$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!"; 
} 
?> 

它的PHP代碼和工作完全正常,但我要實現不PHP在Java服務器端代碼。

我用Google搜索和鏈接enter link description here

InputStream in = request.getInputStream(); 
     BufferedReader r = new BufferedReader(new InputStreamReader(in)); 
     StringBuffer buf = new StringBuffer(); 
     String line; 
     while ((line = r.readLine())!=null) { 
     buf.append(line); 
     } 
     String s = buf.toString(); 

我是新來的Java找到的代碼,以便DONOT知道如何編寫代碼。我安裝了NetBeans netbeans-7.1.1-ml-javaee

有人可以告訴我,如果這個代碼是正確的,如何把它放在文件或哪種類型的文件。我已經創建了項目,但不知道如何將此代碼放入文件。

編輯:

的Andriod代碼工作正常......我想開發服務器代碼來獲取並保存文件

回答

5

我希望這個代碼可以幫助ü

try { 
     HttpClient client = new DefaultHttpClient(); 
    HttpPost post = new HttpPost(Image_url); 
    MultipartEntity mpEntity = new MultipartEntity(); 
    File file = new File(selectedImagePath); 
    ContentBody cbFile = new FileBody(file, "image/jpeg");   
    mpEntity.addPart("photo", cbFile); 
    mpEntity.addPart("user_id", new StringBody(SmallyTaxiTabbar.unique_ID)); 
    mpEntity.addPart("password", new StringBody(SmallyTaxiTabbar.password)); 
    post.setEntity(mpEntity); 
    HttpResponse response1 = client.execute(post); 
    HttpEntity resEntity = response1.getEntity(); 
    String Response=EntityUtils.toString(resEntity); 
    Log.d("PICTUREServer Response", Response); 
    JSONArray jsonarray = new JSONArray("["+Response+"]"); 
    JSONObject jsonobject = jsonarray.getJSONObject(0); 
    alert=(jsonobject.getString("alert")); 
    client.getConnectionManager().shutdown(); 
    } 
    catch (Exception e) { 
       Log.e("TAGPost", e.toString());  
    } 

哪裏SmallyTaxiTabbar.unique_ID,密碼是參數值

* 我希望這段代碼能幫助你! *

+0

它是服務器代碼還是客戶端代碼? – Azhar 2012-04-13 09:28:08

+0

是的,它是客戶端代碼 – 2012-04-13 09:31:55

+0

其實..我想要服務器代碼。 – Azhar 2012-04-13 10:48:25

0

Apache Commons FileUpload庫應該幫助您處理從一個服務器點在Java中POST請求的內容。如果需要,它可以與Servlet集成。

特別是,它會爲您處理multipart/form-data內容(如果您直接逐行讀取請求的InputStream,您將不得不手動執行該操作)。

相關問題