2012-01-21 37 views
4

我想將圖像上傳到PHP頁面以及有關圖像的其他信息,以便PHP頁面知道如何處理它。目前,我越來越使用它:Android:將文件與其他POST字符串一起上傳到頁面

URL url = new URL("http://www.tagverse.us/upload.php?authcode="+WEB_ACCESS_CODE+"&description="+description+"&userid="+userId); 
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); 
connection.setDoOutput(true); 
connection.setRequestMethod("POST"); 

OutputStream os = connection.getOutputStream(); 
InputStream is = mContext.getContentResolver().openInputStream(uri); 
BufferedInputStream bis = new BufferedInputStream(is); 
int totalBytes = bis.available(); 

for(int i = 0; i < totalBytes; i++) { 
    os.write(bis.read()); 
} 
os.close(); 

BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 
String serverResponse = ""; 
String response = ""; 

while((response = reader.readLine()) != null) { 
    serverResponse = serverResponse + response; 
} 
reader.close(); 
bis.close(); 

是否有一個更優雅的解決方案,除了有一個GET/POST混合?我覺得這是蠻橫的,但我知道這是一個完全可以接受的解決方案。如果有更好的方法來做到這一點,我會很高興指出正確的方向。謝謝!

PS:我所熟悉的你會如何,在正常情況下,一個PHP頁面通過POST互動:

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost("http://www.tagverse.us/login.php"); 

try { 
    List<NameValuePair> pairs = new ArrayList<NameValuePair>(); 
    pairs.add(new BasicNameValuePair("authcode", WEB_ACCESS_CODE)); 
    pairs.add(new BasicNameValuePair("username", username)); 
    pairs.add(new BasicNameValuePair("password", password)); 
    post.setEntity(new UrlEncodedFormEntity(pairs)); 
    client.execute(post); 
} 

基本上我想要做的就是這兩種方法結合起來的東西,而是因爲我使用HttpURLConnection對象而不是HttpPost對象,並不像合併兩者那麼簡單。

謝謝!

回答

1

你可以嘗試看看我加入這個類似的問題的答案: https://stackoverflow.com/a/9003674/472747

下面是代碼:

byte[] data = {10,10,10,10,10}; // better get this from a file or memory 
HttpClient httpClient = new DefaultHttpClient(); 
HttpPost postRequest = new HttpPost("server url"); 
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg"); 
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
reqEntity.addPart("image", bab); 

FormBodyPart bodyPart=new FormBodyPart("formVariableName", new StringBody("formValiableValue")); 
reqEntity.addPart(bodyPart); 
bodyPart=new FormBodyPart("formVariableName2", new StringBody("formValiableValue2")); 
reqEntity.addPart(bodyPart); 
bodyPart=new FormBodyPart("formVariableName3", new StringBody("formValiableValue3")); 
reqEntity.addPart(bodyPart); 
postRequest.setEntity(reqEntity); 
HttpResponse response = httpClient.execute(postRequest); 
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); 
String line = null; 
while((line = in.readLine()) != null) { 
    System.out.println(line); 
} 
相關問題