SharePoint REST show current user profile picture - sharepoint

When getting the URL from the current user's profile via REST, the image tag is not able to display when the src is updated:
<img id="escMyPic" src="" alt="" />
<script type="text/javascript">
$.ajax({
url: strURL + "/_api/sp.userprofiles.peoplemanager/getmyproperties",
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
},
success: MyPictureSucceeded,
error: MyPictureFailed
});
function MyPictureSucceeded(data) {
if(data.d.PictureUrl != null) {
$('#escMyPic').attr('src', data.d.PictureUrl);
}
}
function MyPictureFailed() {
alert('Error: Unexpected error loading profile picture.');
}
</script>
The return url looks like this in SharePoint Online:
https://tenant-my.sharepoint.com:443/User%20Photos/Profile%20Pictures/email_address_MThumb.jpg?t=63601764394
It redirects to:
https://tenant-my.sharepoint.com/User%20Photos/Profile%20Pictures/email_address_MThumb.jpg?t=63601764394
Using browser dev tools, you see the mime type that comes back is not image/jpg but text/plain. I've removed the query string parameter, and even placed the hard coded URL in the image tag src, but it just doesn't display. Also the response body in the dev tools is blank. It appears to be redirecting and authenticating before showing.
When placing the hard coded URL in the browser address bar, the picture shows fine, and the dev tools response header shows the picture as the contents of the URL, and the MIME type is image/jpg.
How do you get the profile image to show from a REST call?

In addition to /_api/sp.userprofiles.peoplemanager/getmyproperties endpoint which returns PersonalUrl property, user profile picture could be requested via _layouts/15/userphoto.aspx?size=<size>&accountname=<accountname> page, where
size - could be set to S/M/L which stands for Small/Medium/Large
image size
accountname - user account name
Example
var url = getMyPictureUrl(_spPageContextInfo.webAbsoluteUrl,_spPageContextInfo.userLoginName,"M");
$('#escMyPic').attr('src', url);
where
function getMyPictureUrl(webUrl,accountName,size){
return webUrl + "/_layouts/15/userphoto.aspx?size=" + size + "&accountname=" + accountName;
}

Related

ADAL.js - what is the IFrame target origin for embedding PowerBI dashboard

I'm using the PowerBI REST API along with ADAL.js and getting Dashboards. I want to embed a Dashboard in an IFrame. I'm using Angular.JS
So what did was something like this. Notice I have used "*" as the IFrame Target Origin. dashboardEmbedUrl is obtained from the API call
<iframe id="PBDashboard" ng-show="dashboardVisible" src="{{dashboardEmbededUrl}}" frameborder="0" style="height: 100vh; width: 100%"></iframe>
and in my controller
var iframe = document.getElementById("PBDashboard")
const loadIframeDashboardEventListner = function() {
const token = localStorage.getItem('adal.access.token.keyhttps://analysis.windows.net/powerbi/api');
iframe.contentWindow.postMessage(JSON.stringify({
action: "loadDashboard",
accessToken: token
}), "*") //target is *. what should be the specific URL needed here
}
and
iframe.addEventListener("load",loadIframeDashboardEventListner);
This works perfectly fine but using "*" triggers a security warning in SonarCloud. It says to specify a target. I'm not sure what the target should be. The API call also gives a webUrl along with the embedUrl. I used the webUrl instead of the "*" and it rendered the IFrame data but also gave the following error in console

Base64 encoded image sent using sendgrid not displayed in mails

I am trying to send a logo image in the HTML using sendGrid mailing service. I went through a lot of articles and tried a lot but still could not figure out on how to display inline image using content_id.
I went through following links but still could not make it work:
[Link1][1]: https://sendgrid.com/blog/embedding-images-emails-facts/
[Link2][2]: https://github.com/sendgrid/sendgrid-nodejs/issues/841
Few of the answers suggest to add image as a base64 string in HTML but that does not work with few web mailing clients.
Here is my code:
`
try
{
const msg = {
to: `${customerData.raw[0].invoicemail}`, // List of receivers email address
from : 'xxxx#xxx.com',
subject: `${subject}`, // Subject line
html: emailData, // HTML body content
attachments:
[
{filename:`${filename}`,content:invoice,type:"application/pdf"},
{filename:'logo.jpg',content:logoImageData,content_id:'logo',type:"image/jpg",disposition:"inline"}
],
}
sgMail.send(msg)
//return this.mailerService.sendEmail(msg)
}
catch
{
return false
}`
And here is the HTML block:
<img src = "content_id:logo" alt = "Logo Image" width=140 height=20>
Also, the image is being received as an attachment but is not displayed.
Sorry for the very late reply, I've also had trouble getting my image to display using SendGrid.
#Abhijeet, have you tried replacing src = "content_id:logo" with src="cid:logo"?
For other beginners, like myself, using SendGrid I will include the other steps that #Abhijeet already has done.
Upload and convert your image file to base64 (we'll call this logoImageData).
We want to replace the beginning of the base64 encoded image string using String.prototype.replace().
export const cleanLogoImageData = logoImageData.replace('data:image/jpeg;base64,' , '')
Now, in the attachments for mail data for SendGrid, you need to add these to your object: filename, content, contentType, content_id, and disposition.
const msg = {
attachments: [
{
filename: "logo.jpg",
content: cleanLogoImageData,
contentType: "image/jpeg",
content_id: "logo",
disposition: "inline",
},
],
}
content_id and disposition: "inline" are what got my logo to show.
Finally, in the html file holding your <img />, you must set the src as cid:logo or whatever your content_id is. And moreover, it's recommended to add align="top" and display: block in your img tag for better and consistent cross-platform email display of the image.
<img align="top"
style="display: block"
src="cid:logo"
alt="company logo"
/>

Create a SP 2013 site through the REST API via Jquery AJAX

I am trying to create a SP 2013 site through the REST API via Jquery AJAX. I have extracted the REQUEST_DIGEST from the '/_api/contextinfo' call. Next, while trying to set the X-RequestDigest header for the '/_api/web/webinfos/add' call ,a pre-flight request with method 'OPTIONS' is sent by the browser which is getting a HTTP 403 response code. As per my understanding , it is expecting the FedAuth cookie , while the browser, according to the CORS principle is not sending the authentication info. It seems that the 'OPTIONS' verb need to be configured on the SP 2013 and I have not found any clear solution for this. Is my understanding correct , in which case can anyone provide a solution ?
I created this code that works on my Sharepoint 2013 environment.
First, I try my ajax request with a relative URL like this : /_api/web/webinfos/add
The resquest result in a 403 Forbidden.
Then I retry with : _spPageContextInfo.webAbsoluteUrl + "/_api/web/webinfos/add"
and this time it works fine.
The reason is that my site collection URL pattern is :
http://domain/manage-path/site-collection
So when I use a relative URL /_api/web/webinfos/add its the same as using :
http://domain/_api/web/webinfos/add
Because its not the address of the current site collection Sharepoint returns a Cross-Site Scripting error.
But When I use _spPageContextInfo.webAbsoluteUrl + "/_api/web/webinfos/add" it give me the full URL of the site collection :
http://domain/manage-path/site-collection/_api/web/webinfos/add
Here is the complete script :
<script language="JavaScript" type="text/javascript">
function createSubsiteUsingREST(data,siteTitle,siteUrl,siteDescription) {
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/webinfos/add",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
data: JSON.stringify({
'parameters': {
'__metadata': {
'type': 'SP.WebInfoCreationInformation'
},
'Url': siteUrl,
'Title': siteTitle,
'Description': siteDescription,
'Language': 1033,
'WebTemplate': 'sts',
'UseUniquePermissions': true
}
}),
success:function(){
alert('SubSite Created with success!');
},
error:function(){
alert('oups! An error occured during the process of creating this new SubSite!');
}
});
}
$(document).ready(function() {
$('#btnCreateSubSiteWithREST').on('click',function() {
var siteTitle = $('#txtSiteTitle').val();
var siteUrl = $('#txtSiteUrl').val();
var siteDescription = $('#txtSiteDescription').val();
createSubsiteUsingREST(siteTitle,siteUrl,siteDescription);
});
});
</script>
<input type="button" id="btnCreateSubSiteWithREST" value="Create New SubSite Using REST">
<div><label>Title of the SubSite : </label><input type="text" id="txtSiteTitle"></div>
<div><label>URL of the SubSite : </label><input type="text" id="txtSiteUrl"></div>
<div><label>Description of the SubSite : </label><input type="text" id="txtSiteDescription"></div>
Hope this help!

Instagram: Get oEmbed using Media ID

Say, I have a media ID (eg. 1075297042445691366_195350057). How to get the Embed HTML using the oEmbed API?
This API accepts only shortcode (which is different from media ID).
Or How to get the shortcode of an media ID?
Any media object returned by the API has a field called 'link' that is the URL representation of the media. You can use this link as 'url' parameter of the oembed endpoint.
If anyone finds this question in the future I spent quite a while trying to solve it.
This implementation deserves 99.9% credit to this answer by Nick Hanshaw. All I did was include a CDN link to the BigInteger.js library which is required, but not part of Nick's code. This is currently working for me right now by passing the Media ID as a string into the function, then returning the full string of the Instagram photo URL:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.40/BigInteger.min.js"></script>
<script type="text/javascript">
function getInstagramUrlFromMediaId(media_id) {
var alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
var shortenedId = '';
media_id = media_id.substring(0, media_id.indexOf('_'));
while (media_id > 0) {
var remainder = bigInt(media_id).mod(64);
media_id = bigInt(media_id).minus(remainder).divide(64).toString();
shortenedId = alphabet.charAt(remainder) + shortenedId;
}
return 'https://www.instagram.com/p/' + shortenedId + '/';
}
</script>

Meteor Facebook Profile Picture not Displaying

On first sign I have the following code:
Accounts.onCreateUser(function(options,user){
if (typeof(user.services.facebook) != "undefined") {
user.services.facebook.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large";
}
return user;
});
Which results in the following URL string
http://graph.facebook.com/[myfacebookid]/picture/?type=large
Yet when it renders that url and returns
<img scr="http://graph.facebook.com/[myfacebookid]/picture/?type=large" alt="My Name">
All I see is a broken image. How can I pull this in so that it renders the facebook profile picture?
I use a helper function based off of the Facebook ID of the user to grab the image on the server. I notice my url has /picture? and your has /picture/? Hope this helps.
userPicHelper: function() {
if (this.profile) {
var id = this.profile.facebookId;
var img = 'http://graph.facebook.com/' + id + '/picture?type=square&height=160&width=160';
return img;
}
},
I don't know how I missed this before, but is this the src attribute on the image tag is actually written as scr:
<img scr=
Should be...
<img src=
You have http instead of https.
So:
"https://graph.facebook.com/" + id + "/picture/?type=large";
This was my problem.

Resources