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

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?

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!

Nativescript: How to create a JS File object from file path?

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

Flutter NetworkImage handle 403 error

In my Flutter mobile app while loading profile image of users through NetworkImage(), I am getting 403 status code in response.
How can I handle this by displaying an Image from my assets folder in case of 403 status code or if image URL is broken etc.
Currently I've handled it by sending a HTTP GET request to the image URL and checking if the status code is 200. If it is 200 I use the NetworkImage() or else I use AssetImage() to load the image and use a FutureBuilder() to build the Widget.
While this works perfectly, I feel this a lot of trouble for handling such a small scenario and it can be done in a better way that I am unaware of.
What is the best way to handle such scenarios?
Please try below approach. Here, If image is available, It will load network image else it will redirect to the error callback. In error callback you can return the widget you want. In your case, you want to load from asset so you can use it like as below. If you want to check error status code, you need to parse the exception that I have print.
Image.network('https://www.outbrain.com/techblog/wp-content/uploads/2017/05/road-sign-361513_960_720.jpg',
errorBuilder: (BuildContext context, Object exception, StackTrace? stackTrace) {
print("Exception >> ${exception.toString()}");
return Image.asset('assets/images/lake.jpg');
},
)
You did it simple for this scenario, I didnt see any trouble:
if (response.statusCode == 200) {
return NetworkImage();
} else {
return AssetImage();
}
I achieved this by using precacheImage. This will precache your image to flutter cache. It also has a onError function where you can handle errors while caching the image.
String validatedUrl;
precacheImage(
NetworkImage(urlToCheck),
context,
onError: (
exception,
stacktrace,
) {
print(exception.toString());
setState(() {
validatedUrl = '';
});
},
).whenComplete(() {
if (validatedUrl == null) {
setState(() {
validatedUrl = urlToCheck;
});
}
});
Then validatedUrl is either null, empty or carries the validated url.
null -> not validated yet
empty -> error while downloading image
url -> successfully downloaded image

Android- Sharing local storage on multiple WebViews/Windows

I'm developping a mobile application, which should connect to a web server. The application is written with jQM and simply imported in an android web view. I tried to solve this problem using the jStorage plugin, but it seems that it's impossible to share the local storage between the different pages. So I tried to implement this, but it does not work and continues sending null.
Here are my code samples:
Javascript:
function getToken(authCode) {
var jsonUrl = mainUrl + "/auth/authorizeToken?grant_type=authorization_code&client_id=bc89fb879a64eb8e422b94d5c39&client_secret=b5c2974b78f7f3f7aee2bed182&redirect_uri=redirection&code="+authCode;
$.ajax({
url: jsonUrl,
type: "GET",
dataType: "jsonp",
success: function(data) {
localStorage.setItem( "access_token", data.access_token);
localStorage.setItem( "refresh_token", data.refresh_token);
localStorage.setItem( "logged", "true");
}
});
}
function valTokens() {
access_token = localStorage.getItem("access_token");
refresh_token = localStorage.getItem("refresh_token");
}
After that the values are set to null. The .java files are the same as in the sample from the link given.

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

Categories

Resources