Has anyone been able to accomplish sending a multipart/form-data
POST in Android with Volley yet? I have had no success trying to upload an image/png
using a POST request to our server and am curious if anyone has.
I believe the default way to do this would be to override public byte[] getPostBody()
in the Request.java
class and attach the File
there with a blank Header key for the boundary. However, converting my file to a String
for the Map<String, String> postParams
and then having it encoded again seems obtuse and not really elegant. Also I've been unsuccessful in my attempts. This is really the only thing holding us back from switching to this library.
Anyway, all thoughts and answers are extremely appreciated. Thank you for your help.
As mentioned in the presentation at the I/O (about 4:05), Volley "is terrible" for large payloads. As I understand it that means not to use Volley for receiving/sending (big) files. Looking at the code it seems that it is not even designed to handle multipart form data (e.g. Request.java has getBodyContentType() with hardcoded "application/x-www-form-urlencoded"; HttpClientStack::createHttpRequest() can handle only byte[], etc...). Probably you will be able to create implementation that can handle multipart but If I were you I will just use HttpClient directly with MultipartEntity like:
You may need newer HttpClient (i.e. not the built-in) or even better, use Volley with newer HttpClient
Another solution, very light with high performance with payload large:
Android Asynchronous Http Client library: http://loopj.com/android-async-http/
Sample Usage
First answer on SO.
I have encountered the same problem and found @alex 's code very helpful. I have made some simple modifications in order to pass in as many parameters as needed through HashMap, and have basically copied
parseNetworkResponse()
from StringRequest. I have searched online and so surprised to find out that such a common task is so rarely answered. Anyway, I wish the code could help:And you may use the class as following:
A very simple approach for the dev who just want to send POST parameters in multipart request.
First define these constants :
Add a helper function to create a post body for you :
Override getBody() and getBodyContentType
This is my way of doing it. It may be useful to others :