2011-11-08 48 views
4

我知道這是重複的問題。有很多類似的問題在堆棧溢出,但我問這個問題,因爲我不明白我可以如何用Image發佈一些數據。我如何發佈關鍵/值對與android

我想通過名字和姓氏與圖像到服務器。 現在我仍然嘗試過。

URL connectURL; 
connectURL = new URL("some URL"); 
File sdImageMainDirectory = new File("/sdcard"); 
String existingFileName = sdImageMainDirectory.toString() +"/image.jpg"; 

String lineEnd = "\r\n"; 
String twoHyphens = "--"; 
String boundary = "*****"; 
String Tag="3rd"; 
try 
{ 
    HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection(); 
    conn.setDoInput(true); 
    conn.setDoOutput(true); 
    conn.setUseCaches(false); 
    conn.setRequestMethod("POST"); 

    conn.setRequestProperty("Connection", "Keep-Alive"); 
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); 

    DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); 

    dos.writeBytes(twoHyphens + boundary + lineEnd); 
    dos.writeBytes("Content-Disposition: form-data; name=\"firstname\"" + lineEnd); 
    dos.writeBytes("Dharmendra"); 
    dos.writeBytes(lineEnd); 

    dos.writeBytes(twoHyphens + boundary + lineEnd); 
    dos.writeBytes("Content-Disposition: form-data; name=\"lastname\"" + lineEnd); 
    dos.writeBytes("Patel"); 
    dos.writeBytes(lineEnd); 

    dos.writeBytes(twoHyphens + boundary + lineEnd); 
    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd); 
    dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd); 
    dos.writeBytes(lineEnd); 

    int bytesAvailable = fileInputStream.available(); 
    int maxBufferSize = 1024; 
    int bufferSize = Math.min(bytesAvailable, maxBufferSize); 
    byte[] buffer = new byte[bufferSize]; 

    int bytesRead = fileInputStream.read(buffer, 0, bufferSize); 

    while (bytesRead > 0) { 
     dos.write(buffer, 0, bufferSize); 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
    } 
    dos.writeBytes(lineEnd); 
    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 

    fileInputStream.close(); 
    dos.flush(); 
    dos.close(); 
}catch (MalformedURLException ex) { 
    Log.e(Tag, "error: " + ex.getMessage(), ex); 
} 
catch (IOException ioe) { 
    Log.e(Tag, "error: " + ioe.getMessage(), ioe); 
} 
+0

你重複行'內容處置:對於文件格式,數據...'兩次。那應該在那裏嗎?我猜想第二行應該是設置一個「Content-Type」。 – Thor84no

+0

這是沒有問題,這個重複行我試過了 – Dharmendra

+0

@Dharmendra你檢查了我的文章? – Venky

回答

11

檢查這個代碼添加額外的價值來上傳圖片到服務器:

public class Task_TurnoutPost extends AsyncTask<Void, Void, Void> { 
     private final ProgressDialog dialog = new ProgressDialog(ActivityName.this); 
     JSONObject object_feed; 
     // can use UI thread here 
     protected void onPreExecute() { 
      this.dialog.setMessage("Loading..."); 
      this.dialog.setCancelable(false); 
      this.dialog.show(); 
     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 
      // TODO Auto-generated method stub 
      try { 

       HttpClient httpClient = new DefaultHttpClient(); 
       HttpPost postRequest = new HttpPost("Your LINK"); 
       MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); 
       reqEntity.addPart("F_Name", new StringBody("F_Name")); 
       reqEntity.addPart("L_Name",new StringBody("L_NAME")); 
       try{ 
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        bitmap.compress(CompressFormat.JPEG, 75, bos); 
        byte[] data = bos.toByteArray(); 
        ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg"); 
        reqEntity.addPart("picture", bab); 
       }catch(Exception e){ 
        //Log.v("Exception in Image", ""+e); 
        reqEntity.addPart("picture", new StringBody("")); 
       } 

       postRequest.setEntity(reqEntity); 
       HttpResponse response = httpClient.execute(postRequest); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8")); 
       String sResponse; 
       StringBuilder s = new StringBuilder(); 
       while ((sResponse = reader.readLine()) != null) { 
        s = s.append(sResponse); 
       } 
       object_feed = new JSONObject(s.toString()); 
       success_response=object_feed.getString("status"); 
       Log.v("Response for POst", s.toString()); 
      } catch (Exception e) { 
       Log.e("e.getClass().getName()", ""+e); 
      } 
      return null; 
     } 

     @Override 
     protected void onPostExecute(Void result) { 
      if (this.dialog.isShowing()) { 
       this.dialog.dismiss(); 
      } 
     } 

    } 

位在哪裏是你的位圖。除了它添加一個圖書館和download it

Check this for you reference

+0

是的,它的工作感謝 – Dharmendra

+0

你的代碼工作得很好...它對我非常有幫助...感謝一個很... – AndroidRaji

+0

@AndroidRaji這聽起來很棒!!!! – Venky

0

我實際上在這裏使用Http標題來發布鍵值對。像這樣

conn.setRequestProperty("firstName", "Stephen"); 
conn.setRequestProperty("lastName", "glansburg"); 

然後在您的服務器端,您可以查看該元信息的http標題。

+0

它將如何獲取或訪問的PHP代碼? –

+1

@SamadhanMedge看到這篇文章的PHP請求頭文件:http://stackoverflow.com/questions/541430/how-do-i-read-any-request-header-in-php –