I have this Android app build on Cordova-2.2.0, I'm using node on the server side. There is a part where an image needs to be send to the server, either from the camera or a file. The image is sucesfully uploaded to the server, but when it is saved it seems to be damaged. If I open the image on the notepad it has this "extra header" on the file. Besides that all the file is just the same. Here is my code on the client:
function getPhoto() {
navigator.camera.getPicture(uploadPhoto,
function(message) { alert('No image selected');},
{ quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
);
}
function uploadPhoto(imageURI) {
var largeImage = document.getElementById('Image');
largeImage.style.display = 'block';
largeImage.src = imageURI;
var options = new FileUploadOptions();
options.fileKey="file";
options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
options.mimeType="image/jpg";
options.chunkedMode = false;
var ft = new FileTransfer();
ft.upload(imageURI, "http://10.8.13.92:8082", win, fail, options);
}
And this is the code on the server:
http.createServer(function (req,res){
var fs = require('fs');
var imagen = fs.createWriteStream("imagen.jpg",{'flags':'a'});
req.addListener('response',function(response){
})
});
req.addListener('data',function(chunk){
imagen.write(chunk,encoding='binary');
});
req.on('end',function(){
imagen.end();
console.log('File written');
});
}).listen(8082);
I know the problem is on the server, but I can't find anything different from this to write the .jpg file.
From documentation:
The FileTransfer object provides a way to upload files to a remote server using an HTTP multi-part POST request.
You are trying to writing all reqest data to image file but request data is not just binnary image data. It contains file in HTTP multi-part format and need to be parsed before writing to file.
Simplest way to do it - using connect with bodyParser middleware.
Sample app:
var http = require('http');
var connect = require('connect');
var app = connect();
var server = http.createServer(app);
app.use(connect.bodyParser());
app.use(function(req, res) {
console.log(req.files); // Here is object with uploaded files
});
server.listen(8082);
You can find path to uploaded file in req.files object and move it to needed destination.