2016-03-02 122 views
1

我怎樣才能發送圖像到服務器沒有名稱值對?我知道這是基本的問題,但在stackoverflow中沒有明確的答案。我們如何使用-POST-方法? (正如你知道名稱 - 值對已折舊)。發送圖像到服務器

+0

可以使用namevalue對,如果你想 –

+0

看看我的答案[這裏](http://stackoverflow.com/questions/29534340/missing-file-error-while-uploading-file-to-server - 使用-HTTP-POST#29624050)。 – Exception

+0

http://stackoverflow.com/questions/29966762/upload-image-using-android-php/29967361#29967361 –

回答

1
public String postPhotoUploadRequest(File imageFile) { 
     URL url; 
     String response = ""; 
     int responseCode = -1; 
     try { 
      url   = new URL("your url"); 

      HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
      conn.addRequestProperty("Content-Type", "binary/octet-stream"); 
      conn.setDoOutput(true); 
      conn.setReadTimeout(20000); 
      conn.setConnectTimeout(20000); 
      conn.setRequestMethod("POST"); 

      DataOutputStream writer  = new DataOutputStream(conn.getOutputStream()); 
      Bitmap bmp = ImageUtils.filePathToBitmap(imageFile.getPath()); 
      if(bmp != null) { 
       ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
       bmp.compress(Bitmap.CompressFormat.JPEG, 50, bos); 
       InputStream input = new ByteArrayInputStream(bos.toByteArray()); 

       byte[] buffer = new byte[1024]; 
       for (int length = 0; (length = input.read(buffer)) > 0;) { 
        writer.write(buffer, 0, length); 
       } 
       writer.flush(); 
       writer.close(); 
      } 

      responseCode = conn.getResponseCode(); 

      if (responseCode == HttpsURLConnection.HTTP_OK) { 
       String line; 
       BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
       while ((line = br.readLine()) != null) { 
        response += line; 
       } 
      } else { 
       response   = "Response Code : " + responseCode; 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return response; 
    }