I'd like to send image from android app to node.js server to save into MongoDB on server side. I use AsyncHttpClient to post request.
My code is like this:
Android ->
RequestParams param = new RequestParams();
param.put("email", email);
param.put("image", file, "image/jpg");
System.out.println("Param : " + param);
HttpClient.post("uploadImg_Profile/", param, new AsyncHttpResponseHandler() {
Node.js ->
app.js->
app.post('/uploadImg_Profile/', function(req, res){
uploadImg_Profile.uploadImg_Profile(req, res);
})
uploadImg_Profile.js->
exports.uploadImg_Profile= function(req, res){
var User = new user({
email : req.body.email,
img : req.body.image
});
//
console.log("req : " + req);
console.log("email : "+ User.email);
console.log("image : " + User.img);
But console.log result is undefined. I respect that this is seen jhgdsfejdi734634jdhfdf like this BSON type result.
How can I get img data?
There is a way to get file's type from File object dynamically?
You need to use the right type of body parser in your node.js code - from the result you are getting, it looks as if you're not interpreting it as a multipart form.
You need to register the middleware to use to interpret the POST, for example, using the multer parser:
app.js:
var multer = require('multer');
app.use(bodyparser.json());
app.use(multer({ inMemory: true, putSingleFilesInArray: true }));
app.post('/uploadImg_Profile/', function(req, res){
uploadImg_Profile.uploadImg_Profile(req, res);
});
uploadImg_Profile.js:
exports.uploadImg_Profile= function(req, res){
var User = new user({
email : req.body.email,
img : req.files['image'][0].buffer
});
console.log("req : " + req);
console.log("email : "+ User.email);
console.log("image : " + User.img);
}
Multer will also populate various other properties about the file, so you should be able to retrieve the type of the image from that using:
req.files['image'][0].mimetype
See the multer page on github for all the goodness.
EDIT: Added bodyparser.json as well as multer.
It is solved.
It is possible that both app.use(bodyparser) and app.use(multer) are used simultaneously.
app.use(bodyparser.json())
app.use(multer())
Like this.
And my previous problem is another points.
I don't know exactly what make it doing. I just change express version from 3.x to 4.x and test various situation. In this progress, I find out that req has image buffer properly, and can get buffer data.
Thanks Mark and all of you intereted in my question.
Related
I'm using nativescript-imagepicker plugin to select images from phone gallery. One of the things this plugin allows me to get, is the path to the file.
I need to be able to upload this selected file to a server, using form data. For that i need to create a file object first.
How can i use a file path, to create a file object?
For uploading images from the photo gallery I would highly suggest using Nativescsript background http. To upload the images to the server you will have to save them within the app so that they can be uploaded. I followed the example shown here Upload example.
Once you have saved the images locally if you want additional data you will need to use multipartUpload and construct a request that would look something like this.
let BackgroundHTTP = require('nativescript-background-http')
let session = BackgroundHTTP.session('some unique session id')
let request: {
url: 'your.url.to/upload/images',
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream'
}
description: 'Uploading local images to the server'
}
//photos should have at least the filename from when you saved it locally.
let params = []
photos.forEach(photo => {
params.push({name: photo.name, filename: photo.filename, value: 'ANY STRING DATA YOU NEED'})
}
let task = session.multipartUpload(params, request)
task.on('progress', evt => {
console.log('upload progress: ' + ((evt.currentBytes / evt.totalBytes) * 100).toFixed(1) + '%')
}
task.on('error', evt => {
console.log('upload error')
console.log(evt)
}
task.on('complete', evt => {
//this does not mean the server had a positive response
//but the images hit the server.
// use evt.responseCode to determine the status of request
console.log('upload complete, status: ' + evt.responseCode)
}
Iam new in ionic with sharepoint
I have developed a Mobile app using ionic3 with sharepoint.
Now i have to get user profile picture in my app.
I have tried these are the way can't achieve here is my tried code.
First way tried like this
Passing Url:-
"https://abc.sharepoint.com/sites/QA/_layouts/15/userphoto.aspx?size=M&accountname=admin#abc.onmicrosoft.com"
Second way tried like this
Passing Url:-
These url iam geting using people picker result. PictureURL property
"https://abc.sharepoint.com/User Photos/Profile Pictures/admin_abc_onmicrosoft_com_MThumb.jpg"
These Second method always return
401 UNAUTHORIZED
Above url using to call this method.
public downloadFile(url: string, fileName: string) {
let options = this._apiHeaderForImageURL();
this._http.get(url, options)
.subscribe((data) => {
//here converting a blob to base 64 For internal view purpose in image src
var reader = new FileReader();
reader.readAsDataURL(data.blob());
reader.onloadend = function () {
console.log("Base64", reader.result);
}
//Here Writing a blob file to storage
this.file.writeFile(this.file.externalRootDirectory, fileName, data.blob(), { replace: true })
.then((success) => {
console.log("File Writed Successfully", success);
}).catch((err) => {
console.log("Error While Wrinting File", err);
});
});
}
public _apiHeaderForImageURL() {
let headers = new Headers({ 'Content-Type': 'image/jpeg' });
headers.append('Authorization', 'Bearer ' + localStorage.getItem("token"));
let options = new RequestOptions({ headers: headers, responseType: 3 });
return options;
}
The first api call worked fine result also sucess but image not displayed properly. Thats the problem iam facing.
The result comes an default image like this only.
pls help me to achieve this. Any help warmly accepted.
Iam doning long time stuff to achieve this still i cant achieve pls give some idea.
Is any other way is available to get user picture in ionic 3 using sharepoint?
I am using Bluemix to develop a 'HTTP POST listener' with NodeJS. This server should be the link between an Android Application and a Watson Bluemix Service
This is my code
/*eslint-env node*/
// This application uses express as its web server
// for more info, see: http://expressjs.com
var express = require('express');
// cfenv provides access to your Cloud Foundry environment
// for more info, see: https://www.npmjs.com/package/cfenv
var cfenv = require('cfenv');
// create a new express server
var app = express();
// serve the files out of ./public as our main files
app.use(express.static(__dirname + '/public'));
// get the app environment from Cloud Foundry
var appEnv = cfenv.getAppEnv();
/* 'BODY PARSER - NOT WORKING' */
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); //Assuming JSON ENCODED INPUT
app.use(express.bodyParser({uploadDir:'/images'}));
// start server on the specified port and binding host
app.listen(appEnv.port, '0.0.0.0', function() {
// print a message when the server starts listening
console.log("server starting on " + appEnv.url);
app.post('/handle',function(request,response){
var image64=request.body.encoded_String;
var imageName=request.body.image_name;
/*OK LOG THIS (Encoded Base64 image)*/
console.log("IMG RECEIVED: " + imageName); //OK
console.log("ENCODED: " + image64); // = undefined (chunk problems?)
response.writeHead(200, { "Content-Type": "text/plain" });
response.write('Hello World - Example...\n');
response.end();
});
});
How can I receive a base64 encoded image and save it to a folder?
Thanks for you help!
String with image received in base64 has usually it's format written at the beginning which has to be removed (or at least I used to remove it).
var base64Data = str.replace(/^data:image\/png;base64,/, ""); // str - string with image
Then you have to save it with fs:
fs.writeFile("../dir/to/save/image.png", base64Data, 'base64', function(err) {});
And that's basically all.
i have an error with the Image Upload from Facebook in my Titanium Software, everytime i want to upload an image from my App i get this:
Fail: REST API is deprecated for versions v2.1 and higher
But if i try the same code in the KitchenSink example app, it works perfect:
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'mygraphic.png');
f.write(this.responseData); // write to the file
var blob = f.read();
var data = {
caption: 'behold, a flower',
picture: blob
};
facebook.request('photos.upload', data, showRequestResult);
},
timeout: 10000
});
xhr.open('GET','http://www.pur-milch.de/files/www/motive/pm_motiv_kaese.jpg');
xhr.send();
And in my App:
function showRequestResult(e) {
var s = '';
if (e.success) {
s = "SUCCESS";
if (e.result) {
s += "; " + e.result;
}
} else {
s = "FAIL";
if (e.error) {
s += "; " + e.error;
}
}
alert(s);
}
Ti.App.hs_stats.addEventListener('touchend', function(e){
Ti.App.hs_stats.top = 255;
var xhr = Titanium.Network.createHTTPClient({
onload: function() {
// first, grab a "handle" to the file where you'll store the downloaded data
var f = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory,'mygraphic.png');
f.write(this.responseData); // write to the file
var blob = f.read();
var data = {
caption: 'behold, a flower',
picture: blob
};
Ti.App.fb.request('photos.upload', data, showRequestResult);
},
timeout: 10000
});
xhr.open('GET','http://www.pur-milch.de/files/www/motive/pm_motiv_kaese.jpg');
xhr.send();
});
Looks like you're using the 'old' Facebook module for Appcelerator? I have image uploads working for Profiles and Pages (although Pages is a bit different, I'll explain later). Here's some quick code (I assume you already authenticated with Facebook):
var fb = require('facebook');
fb.appid = "xxxxxxxxxxxxxxxxx";
var acc = fb.getAccessToken();
fb.requestWithGraphPath('me/photos?access_token='+ acc, {picture:image, message: data}, "POST", showRequestResult);
The image variable is just a blob - It comes directly from event.media from a gallery selection or camera intent. data is the text for your status update.
In your tiapp.xml add these lines:
<property name="ti.facebook.appid">xxxxxxxxxxxxxxxxx</property>
and (if you're using Android and iOS - add both or just the platform you're using)
<modules>
<module platform="android">facebook</module>
<module platform="iphone">facebook</module>
</modules>
Now Pages were a bit strange:
var endPoint = 'https://graph.facebook.com/v2.1/' + pid + '/photos?access_token='+ acc;
xhr.open('POST',endPoint);
xhr.send({
message: data,
picture: image
});
You have to use an HTTP Request, as I couldn't get the requestWithGraphPath() to work with pages no matter what I tried.
pid is your page ID and you can get it, or a list of pages you are an admin for like so (again, create a new HTTP Request (xhr) and use this):
xhr.open("GET","https://graph.facebook.com/v2.1/me?fields=accounts{access_token,global_brand_page_name,id,picture}&access_token=" +fb.getAccessToken());
This will return the access token for each page, the global brand name (basically a clean version of the page name), it's id and the profile picture. The access token in this URL is YOUR personal access token (the &access_token= part).
As far as I can tell, these access tokens don't expire for pages, so you can save it in your app somewhere or if you REALLY want to be safe, you could grab a token before each post, but that's a bit much.
BONUS:
If you want to do video posts to pages:
var xhr = Titanium.Network.createHTTPClient();
var endPoint = 'https://graph-video.facebook.com/'+ pid +'/videos?access_token='+ acc;
xhr.open('POST',endPoint);
xhr.setRequestHeader("enctype", "multipart/form-data");
xhr.send({source:video, description:data});
and for profiles:
var acc = fb.getAccessToken();
var xhr = Titanium.Network.createHTTPClient();
var endPoint = 'https://graph-video.facebook.com/me/videos?access_token='+ acc;
xhr.open('POST',endPoint);
xhr.setRequestHeader("enctype", "multipart/form-data");
xhr.send({source:video, description:data});
video is another blob from either your camera or gallery event.media intent and data is the text you want to use for the status update.
I am developing android application using titanium and in my application I need to upload image from gallery to remote server location.I already tried this
button1.addEventListener('click',function(e)
{
Titanium.Media.openPhotoGallery({
success : function(event)
{
var update_pic = Titanium.Network.createHTTPClient();
update_pic.onerror = function()
{
Titanium.API.info('error');
alert(JSON.parse(this.responseText).error);
}
update_pic.onload = function()
{
actInd.hide();
}
update_pic.open('POST','server-address/profile/update.json');
update_pic.send(
{
"user[avatar]":event.media,
"authenticity_token":"sD5hjlI=",
"user[name]":'nilesh',
"commit":"Update Profile"
});
}
})
})
But its not working for me. Process stop at point user[avatar]:event.media,.Is this the proper way to send image to remote server. I also tried this
update_pic.send({
user_avatar : event.media,
authenticity_token : "sD5hjlI=",
user_name : 'nilesh',
commit : "Update Profile"
})
when I send parameter like this, it not sending my http request and When I remove user_avatar : event.media It sending my request mean there is problem with user_avatar.Any solution....Need help. Thank you..........
try adding this line below "var update_pic = ..."
update_.setRequestHeader("ContentType", "image/jpeg");
taken from: http://developer.appcelerator.com/question/9481/how-to-upload-images-with-filename-to-the-server