2017-10-18 48 views
0

我無法弄清楚如何使用multipart/form-data發送帶有圖像的JSON對象。Http POST如何使用multipart/form-data發送JSON文件內部

POST /api/user/update 
{ id: 123, 
    user: { logo: !!here_file!! } 
} 

我試圖把的base64串入標誌字段,只是通過這個JSON對象,但這種方法是不行的,服務器需要內容類型:多重/ form-data的;我無法得到如何做到這一點。我已經瀏覽了很多問題,但沒有找到如何發佈JSON文件以及這個文件。

+0

哪些是您使用在後端側解析它的語言? –

+0

@WalterPalladino不幸的是我不處理任何服務器端。 –

+0

我添加了一些正在爲我工​​作的代碼。希望它可以幫助你。就我而言,後端是PHP。 –

回答

0

這是我使用POST發送到後端的通用方法:

/** 
* putJSONObject 
* 
* @param url 
* @param jsonObject 
* @param timeoutMillis 
* @return 
*/ 
protected static JSONObject putJSONObject (String url, JSONObject jsonObject, int timeoutMillis) throws IOException, JSONException { 

    StringBuilder stringBuilder = new StringBuilder(); 

    HttpURLConnection httpURLConnection; 
    DataOutputStream printout; 

    httpURLConnection = (HttpURLConnection) new URL (url).openConnection(); 
    httpURLConnection.setRequestMethod ("POST"); 
    httpURLConnection.setReadTimeout (timeoutMillis); 
    httpURLConnection.setConnectTimeout (timeoutMillis); 
    httpURLConnection.setDoInput (true); 
    httpURLConnection.setDoOutput (true); 
    httpURLConnection.setUseCaches (false); 
    httpURLConnection.connect(); 

    // Send POST output. 
    printout = new DataOutputStream (httpURLConnection.getOutputStream()); 
    printout.writeBytes ("msg=" + URLEncoder.encode (jsonObject.toString(), "UTF-8")); 
    printout.flush(); 
    printout.close(); 

    InputStreamReader inputStreamReader = new InputStreamReader (httpURLConnection.getInputStream()); 

    int read; 
    char[] buff = new char[4096]; 
    while ((read = inputStreamReader.read (buff)) != -1) { 
     stringBuilder.append (buff, 0, read); 
    } 
    httpURLConnection.disconnect(); 

    return new JSONObject (stringBuilder.toString()); 

} 

的JSON發送被作爲「味精」

和圖像編碼到一個字符串,這是我的代碼:

/** 
* toBase64 
* 
* @param bitmap 
* @return String 
*/ 
public static String toBase64 (Bitmap bitmap) { 
    ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
    byte[] imageBytes = baos.toByteArray(); 
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT); 
    return encodedImage; 
} 

/** 
* fromBase64 
* 
* @param encodedImage 
* @return Bitmap 
*/ 
public static Bitmap fromBase64 (String encodedImage) { 
    byte[] decodedByte = Base64.decode(encodedImage, Base64.DEFAULT); 
    return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length); 
} 

希望它可以幫助你。

0

起初你應該改變方法。在您想要發送JSON對象之前,您必須將圖像(文件)加載到上傳服務器。上傳服務器,它是一個服務器,您將存儲您的圖像,並可以通過引用訪問它。 它看起來像這樣:使用multipart/form-data將圖像上載到服務器並獲取圖像的鏈接。然後你把這個鏈接到您的JSON對象一樣

{ 
    id: 123, 
    user: { logo: https://myuploadserver.com/img123.jpg } 
} 

然後你可以用JSON對象,做你想做

幾個環節的計算器與如何使用數據上傳到上傳服務器的說明的multipart/form-data的:

1. simple HttpURLConnection POST file multipart/form-data
2. upload multipart form data to server