I want to convert and image into base64 format and then upload that onto the server but the base64 string is so large that it gives me error on web that parameter not received.Any idea to send the complete string to the server using the below webservice? Here is below service that i tried.
var xhrAddclient = Titanium.Network.createHTTPClient();
xhrAddclient.open('POST', webservice_url);
xhrAddclient.send({
method : "addclient",
image : base64string,
});
xhrAddclient.setTimeout(10000);
xhrAddclient.onerror = function() {
showAlertBox('Service timed out. Please try again.');
};
xhrAddclient.onload = function() {
showAlertBox("Client added successfully.");
};
Check here: http://www.smokycogs.com/blog/titanium-tutorial-how-to-upload-a-file-to-a-server/
and here: https://wiki.appcelerator.org/display/guides/File+Uploads+and+Downloads#FileUploadsandDownloads-Fileupload
or just:
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.send(file);
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 have prepared an application with image upload. It sends some text and an image.
It's working fine when I add an image and content(text). Unfortunately it's not working when I call the service without an image, see code below,
var params = {
file :$.selectedImageVw.image, //if file is not selected it will send as null
UserId : Ti.App.userID,
postContent : $.postMessage.value
};
var xhr = Titanium.Network.createHTTPClient();
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
progressVw.hide();
// callback("Success");
// alert(this.responseData);
progressVw.hide();
xhr = null;
}
};
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.setRequestHeader('enctype', 'multipart/form-data');
xhr.setRequestHeader('Content-length', params.length);
xhr.open("POST", "uploadUrl");
xhr.send(params);
I hope someone can help me.
Thanks in advance!!
Try to use a service like http://requestb.in/ to check if the requests made by the client are the issue or the backend you use.
#FokkeZandbergan thanks for your respone,
This issue resolve by very simple modification'
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
changed to
xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded");
Now its working with both imags and without images.
It may help to some one . :)
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.
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