android


uploading image with volley and multer node js


I am trying to upload single image to node js server with several strings. So far my code sends the image to the server as POST variables i.e. in req.body. While the multer in Node JS looks for image in req.file. Hence I am unable to upload the image and keep getting 402 Proxy Error.
Android Code
// String Parameters
Map<String, String> params = new HashMap<String, String>();
params.put("title", title_text);
params.put("description", description_text);
params.put("location", location_text);
myServerRequest.multipartRequest(
URL,
myServerRequest.getImageByte(selectedImageForUpload),
params,
new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse networkResponse) {
Toast.makeText(PostUpload.this, networkResponse.toString(), Toast.LENGTH_LONG).show();
Log.i("Post UPload", networkResponse.toString());
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Volley Error FOund", "Error: " + error
+ ">>" + error.networkResponse.statusCode
+ ">>" + new String(error.networkResponse.data)
+ ">>" + error.networkResponse.headers.toString()
+ ">>" + error.getCause()
+ ">>" + error.getMessage());
}
}
);
Code for Multipart request class
public class MultipartRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
private final Map<String, String> mHeaders;
private final String mMimeType;
private final byte[] mMultipartBody;
public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] multipartBody, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
this.mHeaders = headers;
this.mMimeType = mimeType;
this.mMultipartBody = multipartBody;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return mMimeType;
}
#Override
public byte[] getBody() throws AuthFailureError {
return mMultipartBody;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
mListener.onResponse(response);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
myServerRequest Class functions
public static void multipartRequest(final String url, byte[] file, Map<String, String> params, Response.Listener<NetworkResponse> success, Response.ErrorListener error) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
try {
// the image file
buildPart(dos, file, "avatar");
// the string params
for (Map.Entry<String, String> entry : params.entrySet()) {
//System.out.println(entry.getKey() + "/" + entry.getValue());
buildTextPart(dos, entry.getKey(), entry.getValue());
}
// send multipart form data necesssary after file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// pass to multipart body
multipartBody = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
MultipartRequest multipartRequest = new MultipartRequest(url, null, mimeType, multipartBody, success, error);
MyVolleyRequest.getInstance(Main.getAppContext()).addToRequestQueue(multipartRequest);
}
private static void buildTextPart(DataOutputStream dataOutputStream, String parameterName, String parameterValue) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"" + parameterName + "\"" + lineEnd);
dataOutputStream.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes(parameterValue + lineEnd);
}
private static void buildPart(DataOutputStream dataOutputStream, byte[] fileData, String fileName) throws IOException {
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"avtar\"; filename=\""
+ fileName + "\"" + lineEnd);
dataOutputStream.writeBytes(lineEnd);
ByteArrayInputStream fileInputStream = new ByteArrayInputStream(fileData);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024 * 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
// read file and write it into form...
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dataOutputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dataOutputStream.writeBytes(lineEnd);
}
Node JS code
router.post('/upload', upload.single('avatar'), function(req, res) {
db.uploadPost(req, 1, function(image) {
response = {};
// Rectify un-useful
if(image.error) {
response.success = false;
response.error = image.error;
response.data = image.data;
} else {
response.success = true;
response.name = req.file.filename;
response.thumb = image.name;
response.type = image.type;
//response.width = image.width;
//response.height = image.height;
}
res.json(response);
});
});
How can I move the avatar from req.body to req.file?
updated
Added Multipart body to request. Now getting 200 but post is still not uploading.
request object doesn't have req.body or req.file now.

Related Links

ListAdapter and Set image from web
How to handle clicks from 2 listviews in 1 ListActivity
Runtime error referencing a resource in string.xml
get the alarm interval
arm-linux-androideabi-g++.exe: CreateProcess: No such file or directory error
Thread-safe progressive downloading in Android
NMEA sentences - PGLOR, GNGSA and QZGSA
Button at Bottom
HttpPost Iphone Versus Android
Not being able to add a textView to LinearLayout through code
Prevent multiple instances of Activity but still use onActivityResult
BootupReceiver in Android 3.1
TableLayout not shrink all images
How to update Android kernel with zImage?
startActivityForResult doesn't seem to call onActivityResult
WebView using 30% in background in WebViewCoreThread

Categories

HOME
design-patterns
apache-flink
forms
webdriver
toolbox
jelastic
can
nuget
bitbucket-api
javacc
settings
teechart
google-chrome-app
mel
java.util.logging
jxl
favicon
frequency-distribution
atlassian
parameter-passing
azure-iot-hub
standards
aws-sdk
google-content-api
sencha-touch
visual-glitch
ksh
roslyn
jboss6.x
gpio
pylons
shared
android-things
bioinformatics
sqlpackage
vex
twiml
magento-1.8
autodesk-designautomation
papaparse
sammy.js
carriage-return
reverse
apiary.io
git-rewrite-history
graphhopper
projects-and-solutions
railstutorial.org
demo
metawidget
dcmtk
android-ibeacon
subclipse
plr
logback-groovy
lampp
azure-cli
context-sensitive-grammar
spring-data-couchbase
edit
libjpeg
jtree
structuremap4
chromium-os
pytables
grails-plugin
async.js
watch-os-2
mapinfo
observablecollection
freepbx
nservicebus5
turbo-prolog
realsense
phpgrid
gocql
poppler
video-player
extjs-grid
sony-lifelog-api
graphics2d
zxspectrum
apache-spark-1.3
android-vibration
machine-instruction
jama
template-deduction
ora-00904
wxformbuilder
radiant
menubar
cfcache
mbunit
dtmf
node-blade
insert-id
twisted.web
android-sdk-2.3
device-width
web-notifications
fragmenttransaction
usertype
ilasm
koken
uipagecontrol
massive
diagrams
load-time
non-clustered-index
openfaces
blender-2.49
spread
lalr
feasibility
escrow
ifilter
leader

Resources

Encrypt Message