Đây là một cách tiếp cận Đơn giản nếu bạn đang sử dụng thư viện AOSP Volley
.
Mở rộng lớp học Request<T>
như sau-
public class MultipartRequest extends Request<String> {
private static final String FILE_PART_NAME = "file";
private final Response.Listener<String> mListener;
private final Map<String, File> mFilePart;
private final Map<String, String> mStringPart;
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, Map<String, File> file,
Map<String, String> mStringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
this.mStringPart = mStringPart;
entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
buildMultipartEntity();
}
public void addStringBody(String param, String value) {
mStringPart.put(param, value);
}
private void buildMultipartEntity() {
for (Map.Entry<String, File> entry : mFilePart.entrySet()) {
try {
entity.addBinaryBody(entry.getKey(), Utils.toByteArray(new FileInputStream(entry.getValue())), ContentType.create("image/jpeg"), entry.getKey() + ".JPG");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
if (entry.getKey() != null && entry.getValue() != null) {
entity.addTextBody(entry.getKey(), entry.getValue());
}
}
}
@Override
public String getBodyContentType() {
return httpentity.getContentType().getValue();
}
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
httpentity = entity.build();
httpentity.writeTo(bos);
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
Log.d("Response", new String(response.data));
return Response.success(new String(response.data), getCacheEntry());
}
@Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
Bạn có thể tạo và thêm một yêu cầu như-
Map<String, String> params = new HashMap<>();
params.put("name", name.getText().toString());
params.put("email", email.getText().toString());
params.put("user_id", appPreferences.getInt( Utils.PROPERTY_USER_ID, -1) + "");
params.put("password", password.getText().toString());
params.put("imageName", pictureName);
Map<String, File> files = new HashMap<>();
files.put("photo", new File(Utils.LOCAL_RESOURCE_PATH + pictureName));
MultipartRequest multipartRequest = new MultipartRequest(Utils.BASE_URL + "editprofile/" + appPreferences.getInt(Utils.PROPERTY_USER_ID, -1), new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error: ", error.toString());
FugaDialog.showErrorDialog(ProfileActivity.this);
}
}, new Response.Listener<String>() {
@Override
public void onResponse(String jsonResponse) {
JSONObject response = null;
try {
Log.d("jsonResponse: ", jsonResponse);
response = new JSONObject(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
try {
if (response != null && response.has("statusmessage") && response.getBoolean("statusmessage")) {
updateLocalRecord();
}
} catch (JSONException e) {
e.printStackTrace();
}
FugaDialog.dismiss();
}
}, files, params);
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(multipartRequest);