4
我試圖上傳一張圖片到服務器,我從服務器獲取不同的響應,這取決於我發送的實體。用多個參數發送多部分/表單請求?
當我發送
FileBody fb = new FileBody(new File(filePath), "image/jpeg");
StringBody contentString = new StringBody(directoryID + "");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", fb);
entity.addPart("directory_id", contentString);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
// Read the response
String jsonString = EntityUtils.toString(response.getEntity());
我得到的迴應是{"status":"Success","code":"200","message":"File has been uploaded Successfully"}
,如果我以這種方式發送相同的文件
Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
StringBody contentString = new StringBody(directoryID + "");
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file");
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("file", ba);
entity.addPart("directory_id", contentString);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
// Read the response
String jsonString = EntityUtils.toString(response.getEntity());
,我現在得到的迴應是{"status":"Failure","code":"501","message":"Invalid File to upload"}
- 所以我想知道爲什麼兩個響應 之間有差異?
- 我是否以正確的方式發送發佈請求參數?
- 我必須如何以相同的方式發佈視頻?
下面是引用
public void uploadFile(int directoryID, String filePath) {
Bitmap bitmapOrg = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
String upload_url = BASE_URL + UPLOAD_FILE;
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
byte[] data = bao.toByteArray();
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(upload_url);
MultipartEntity entity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
try {
// Set Data and Content-type header for the image
FileBody fb = new FileBody(new File(filePath), "image/jpeg");
ByteArrayBody ba = new ByteArrayBody(data, "image/jpeg", "file");
StringBody contentString = new StringBody(directoryID + "");
// If i do this
entity.addPart("file", fb);
// I get a valid response
// If i do this
entity.addPart("file", ba);
// I get an invalid response
entity.addPart("directory_id", contentString);
postRequest.setEntity(entity);
HttpResponse response = httpClient.execute(postRequest);
// Read the response
String jsonString = EntityUtils.toString(response.getEntity());
Log.e("response after uploading file ", jsonString);
} catch (Exception e) {
Log.e("Error in uploadFile", e.getMessage());
}
}