Click here to Skip to main content
15,891,905 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi
I want to upload image to server. I know I can do multipart-upload but problem is, In my case I have url of image that is on different server. I have to make a ajax call to load that image at client side that I have already done,then make another ajax call to upload that image to server where server side app (i. e. in node.js) is running. On server side I am able to get that image and saved successfully to desired location but the problem is when I open that image then it show image in not correct for or it is corrupted. My code is
JavaScript
// ajax call to download image from wp 
jQuery.ajax({
    url: imageUrl,
    type: 'GET',
    processData : false,
    success: function(res){
        // once image loaded, upload to node server
        var dataObj = {
            "license": license_code,
            "wpImageId": wpImageId,
            "imageName": imageName,
            "imageData": res
        }

        upload_image(formData);        
    },
    error: function(error){
        alert(JSON.stringify(error));
    }
});

// code to upload 
function upload_image(dataObj){
    jQuery.ajax({
        url: hostUrl + "api/v1/service/uploadImageToServer",
        type: "POST",
        data: dataObj,        
         processData: false,
        success: function  (res) {
            if(res.errorCode == 0)
                console.log('success');
            else
                console.log(res.errorCode);                
        },
        error: function(error){
            alert(JSON.stringify(error));
        }
    });
}

// Now server side code is
service.uploadImage = function(request, response){
	var result = new Object();
	result.errorCode = errorCodes.SUCCESS;

	var wpImgId = request.body.wpImageId;
	var imgName = wpImgId + '-img.jpg';
	var imgData = request.body.imageData;

	// First way that I tried
	var wstream = fs.createWriteStream(filename, {'encoding':'binary'});
	wstream.write(imgData);
	wstream.on('finish', function () {
  		console.log('finish');
	});

	wstream.end(function (){
		console.log('end');
		service.pushResponseToClients(request, response, result, null);
	});



	// Second way 
	fs.writeFile(filename, imgData, function(error) {
		if(error){
			console.log(JSON.stringify(error));
			service.pushResponseToClients(request, response, result, null);
			return;
		}
	});
});

I both case able to save the file but image is not in correct format. I am tried to save in .jpg.
I can directly load that image from server but I have to do this in that way.

Please help :)
Posted
Updated 17-Jul-15 23:49pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900