1 | initial version |
Here is a general process for using the Volley library to upload a file on Android:
Here is some sample code that demonstrates this process:
``` RequestQueue requestQueue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<string>() { @Override public void onResponse(String response) { Log.d(TAG, "Response: " + response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e(TAG, "Error: " + error.getMessage()); } }) { @Override public String getBodyContentType() { return "multipart/form-data; boundary=" + BOUNDARY; }
@Override
public byte[] getBody() throws AuthFailureError {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
File file = new File(filePath);
builder.addPart("file", new FileBody(file, ContentType.APPLICATION_OCTET_STREAM, file.getName()));
builder.addTextBody("filename", file.getName());
HttpEntity entity = builder.build();
entity.writeTo(bos);
} catch (Exception e) {
Log.e(TAG, "MultipartEntityBuilder error: " + e.getMessage());
}
return bos.toByteArray();
}
};
requestQueue.add(stringRequest);