I am trying to send a file over http from android application to node.js server.
However, when I receive the file it's size is 0 bytes, although i can read the file's original name.
Do you have any idea what goes wrong here?
Here is the android part:
public class ImageUploader {
public static final String HTTP_LOCALHOST_8081_FILE_UPLOAD = "http://192.168.1.104:8081/file_upload";
public void upload(InputStream inputStream, String extension) {
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams requestParams = prepareRequestParams(inputStream, extension);
asyncHttpClient.post(HTTP_LOCALHOST_8081_FILE_UPLOAD, requestParams, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
error.printStackTrace();
}
});
}
private RequestParams prepareRequestParams(InputStream inputStream, String extension) {
RequestParams requestParams = new RequestParams();
requestParams.put("image", inputStream, "image." + extension, "image/jpeg");
return requestParams;
}}
And here is the node.js part:
var express = require('express')
var multer = require('multer')
var app = express()
var path = require('path')
var uploading = require('./uploading/uploading.js')
var storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads/')
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '_' + Date.now() + path.extname(file.originalname))
}
})
var upload = multer({
storage: storage
})
app.use(express.static('public'));
app.post('/file_upload', upload.single('image'), function(req, res) {
//uploading.openIrfanView(__dirname, req.file.filename)
res.sendStatus(200);
})
var server = app.listen(8081, function() {})
My guess is that either java inputStream
doesn't fit for http multipart
request or I need to use some special node library to read what is send.
Ok, i got it guys.
It's a thing I stumbled upon not for the first time - It's that reading from an input stream empties it out.
I obtained inputStream
from Uri
, then read from it for the first time to display it on the screen of the device and then for the second time to pass it to ImageUploader
and by that time the inputStream
was already empty.
I probably should have pasted that fragment of code to the question.