android


How to multipart data using Android Volley


I am using Volley for calling web request for my app. But as i am Volley for first time. I just want to know that how to upload image/video media data via volley using multipart.
I searched for it many sites, I got some results over
How to send a “multipart/form-data” POST in Android with Volley
But, these methods does'nt look good or efficients. So, Please help me that how to upload media data using volley. Or i should not use Volley, and should go for the previous manual approach
Anyway, all thoughts and answers are extremely appreciated. Thank you for your help.
Don't know if you have got an answer, but if you haven't try this:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
public class MultipartRequest extends Request<String> {
// private MultipartEntity entity = new MultipartEntity();
MultipartEntityBuilder entity = MultipartEntityBuilder.create();
HttpEntity httpentity;
private static final String FILE_PART_NAME = "file";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final Map<String, String> mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener,
Response.Listener<String> listener, 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() {
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
for (Map.Entry<String, String> entry : mStringPart.entrySet()) {
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) {
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response) {
mListener.onResponse(response);
}
}
In order to make it work you must use this java httpclients:
http://hc.apache.org/downloads.cgi
By the time I'm writing this answer (02/07/14) the version I'm using is 4.3.2.
Hope it helps !
You have to use the code below to upload image using multipart with volley. It works like a charm in my app.
public class MultipartRequest extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final String mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<String> listener, File file, String stringPart)
{
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
try
{
entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
#Override
public String getBodyContentType()
{
return entity.getContentType().getValue();
}
#Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
return Response.success("Uploaded", getCacheEntry());
}
#Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
}
I rewrote this to work without a dependency on MultiPartEntity.
public class MultipartRequest extends Request<JSONObject> {
private RequestBody entity;
private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";
private final Response.Listener<JSONObject> mListener;
private final File mFilePart;
private final String mStringPart;
public MultipartRequest(String url, Response.ErrorListener errorListener, Response.Listener<JSONObject> listener, File file, String stringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity() {
entity = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(STRING_PART_NAME, "file")
.addFormDataPart(FILE_PART_NAME, mFilePart.getName(),
RequestBody.create(MediaType.parse(getMimeType(mFilePart)), mFilePart))
.build();
}
#Override
public String getBodyContentType() {
EruditusLog.d("UT_LOG", entity.contentType() + "");
return entity.contentType() + "";
}
#Override
public byte[] getBody() throws AuthFailureError {
BufferedSink bufferedSink;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
bufferedSink = Okio.buffer(Okio.sink(bos));
entity.writeTo(bufferedSink);
bufferedSink.close();
} catch (IOException e) {
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
#Override
protected void deliverResponse(JSONObject response) {
mListener.onResponse(response);
}
static String getMimeType(#NonNull File file) {
String type = null;
final String url = file.toString();
final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
}
if (type == null) {
type = "image/*"; // fallback type. You might set it to */*
}
return type;
}
}

Related Links

Added fragments to viewpager are empty
How can I capture images from a RajawaliSurfaceView or RajawaliTextureView or the Renderer of them at Android?
Can I use Resources.getSystem()?
How do I get the output of an adb shell command using gradle?
JQuery Mobile App - section of code that breaks the entire app
How to show a text in 2 colors in android?
AppCompatActivity Gives Error
ListView getting image value from SQLite lagging
Android Gradle Sync Failed to Sync project
Is there any adb command to mute the call in an ongoing call session?
Reformat Whole Project Files in Android Studio
How to check whether a message has been delivered?
Android Context Menu for any View
Mocking Google Awareness API
How can I use react-native and socket.io-stream together?
Saving and restoring state using fragments

Categories

HOME
eclipse
search
google-cloud-platform
fuelux
youtube-data-api-v3
swt
pdfbox
opendj
simulink
pyqt4
babeljs
jetty
polling
missing-data
discrete-mathematics
project
minecraft-forge
datastage
flash-player
scsi
esoteric-languages
easyphp
forgot-password
template-engine
pyramid
identity-management
solrcloud
googlebot
r-mice
pchart
zxing
moses
interbase
jackson-modules
8051
errbot
openmdao
comparable
ntp
volatile
python-2.6
dumpbin
erb
android-sugarorm
gnat-gps
baidu-map
yowsup
hivemq
modernizr
projects-and-solutions
filesystemwatcher
sim-card
railstutorial.org
opensmpp
spring-mvc-test
apache-stanbol
android-ibeacon
bindingnavigator
tcc
importerror
procfile
jquery-ui-draggable
serde
dotnet-httpclient
netbeans6.8
zenhub
corruption
singleinstance
trigger.io
py2neo
restore
grails-plugin
winusb
webjars
jquery-jscrollpane
dimension
gogs
xdoclet
appscale
cassia
project-organization
dbamp
sklearn-pandas
pushbots
cycle2
httpruntime.cache
rasterize
maybe
concurrentmodification
iokit
lasso
typemock
sha512
alloy-ui
nutiteq
xmltype
showdialog
boost-program-options
mruby
crowd
angular-carousel
verold
ora-00904
vsx
kendo-dataviz
away3d
facebook-timeline
pclzip
resource-management
dopostback
mkv
monotouch.dialog
saleslogix
garbage
cross-database
procedures
tmx
presentation-layer
non-clustered-index
interprocess
scrollbars
qtabbar
purepdf
xpsdocument
application-planning
int64

Resources

Encrypt Message