我個人使用loopj進行客戶端 - 服務器通信,並且可以使用它中的文件發送圖像。添加下面的依賴於你的應用程序gradle這個使用循環J
compile 'com.loopj.android:android-async-http:1.4.9'
然後發送圖像
public void sendAllData() {
String Url = "your url here";
//If any auth is needed
String username = "username";
String password = "password";
Cursor cursor = mContext.getContentResolver().query(Media.EXTERNAL_CONTENT_URI, new String[]{Media.DATA, Media.DATE_ADDED, MediaStore.Images.ImageColumns.ORIENTATION}, Media.DATE_ADDED, null, "date_added ASC");
if (cursor != null && cursor.moveToLast()) {
Uri fileURI = Uri.parse(cursor.getString(cursor.getColumnIndex(Media.DATA)));
fileSrc = fileURI.toString();
cursor.close();
}
// Bitmap compressedImage = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth(username, password);
RequestParams params = new RequestParams();
try {
params.put("pic", storeImage());
} catch (FileNotFoundException e) {
Log.d("MyApp", "File not found!!!" + fileSrc);
}
client.post(Url, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject responseBody) {
//Do what's needed
}
@Override
public void onFailure(int statusCode, Header[] headers, String errorResponse, Throwable error) {
//Print error
}
});
}
private File storeImage() {
String filename = "anyName";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, filename + ".jpg");
try {
outStream = new FileOutputStream(file);
bookImage.compress(CompressFormat.JPEG, 80, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
如何接收服務器上的形象說的是哪的MediaType我應該在REST API使用? –
在這種情況下,Web服務上的媒體類型將爲MediaType.MULTIPART_FORM_DATA – Ishaan