Titanium Appcelerator image upload issue When call service without image - android

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 . :)

Related

How to upload image using apollo iOS client?

I am having a problem with uploading an image in ios apollo client. after I upload an image I get a GraphQlError "createReadStream is not a function".
I could not figure out what has gone wrong?
Mutation
mutation UploadPhoto($input: UploadPhotoInput){
uploadClientPhoto(input: $input){
photo
}
}
Type Detail
type UploadPhotoInput {
photo: Upload
}
type UploadPhotoResponse {
photo: String
}
Following code is not working
class Network {
static let shared = Network()
private lazy var networkTransport = HTTPNetworkTransport(url: URL(string: "http://192.168.10.29:5001/graphql")!, session: .init(configuration: URLSessionConfiguration.default))
private(set) lazy var apolloCient = ApolloClient(networkTransport: networkTransport)
}
Upload image
if let data = singlePhoto.image.jpegData(compressionQuality: 0.8) {
let name = UUID().uuidString
let file = GraphQLFile(fieldName: "\(name)", originalName: "\(name).png",mimeType: "image/png" ,data: data)
let uploadInput = UploadPhotoInput(photo: file.originalName)
let uploadMutation = UploadPhotoMutation(input: uploadInput)
Network.shared.apolloCient.upload(operation: uploadMutation, context: nil, files: [file]) { (result) in
switch result {
case .success(let success):
print(success.data)
case .failure(let error):
print(error.localizedDescription)
}
}
}
This certainly sounds frustrating. I've heard of similar issues with other networking clients, though.
Sounds like apolloCient.upload won't send a GraphQL Multipart Request.
Looks like this blog post covers exactly how to set this up - even including an example repo made for React Native.
Hope that's helpful!

How to Download and view profile picture in ionic 3 with sharepoint?

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?

How to Upload image on server using webservice in titanium android/iOS?

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);

Uploading Image from gallery to remote server (Titanium-android)

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

unable to connect to JSON service in android application of Titanium studio

i am trying to do login application which takes id and password..when i click on logi button then it will connect to our local server by JSON..with the specified URL..the code is..
var loginReq = Titanium.Network.createHTTPClient();
loginReq.onload = function()
{
var json = this.responseText; alert(json);
var response = JSON.parse(json);
if (response.data.status == "success")
{ alert("Welcome ");
}
else
{ alert(response.data.status);
}
};
loginReq.onerror = function(event)
{
alert(event.toSource());
//alert("Network error");
};
loginBtn.addEventListener('click',function(e)
{ if (username.value != '' && password.value != '')
{
var url = 'our local url action=login&id='+username.value+'&pwd='+password.value;
loginReq.open("POST",url);
loginReq.send();
}
else
{
alert("Username/Password are required");
}
});
Here it is not connecting our URl..so it is entering into loginReq.onerror function...instead of loginReq.onload function..why it is throwing run time error.. The same code working fine with Iphone..
The Run Time Error is..
TypeError:Cannot call property toSource in object{'source':[Ti.Network.HttpClient],specified url} is not a function,it is a object.
This is wat the error..please let me Know...
Apparently the toSource() function does not exist in android, as it is an object. Try debugging and see what the object event contains.
You could do that by adding a line above the alert line, and adding a debug line to it.
Look in debug mode and see all variables
"toSource()" is not a documented function for either platform, and I also do not see it in the source for Titanium Mobile. If you aren't getting the error on iOS, I'm guessing it is because the error handler isn't getting called. Perhaps your emulator or device does not have internet access, whereas your iOS simulator or device does?
Regardless, error handling in the HTTPClient normally looks something like this:
loginReq.onerror = function(e)
{
Ti.API.info("ERROR " + e.error);
alert(e.error);
};

Categories

Resources