1

Is there any possibility to change profile picture or uploading a new profile picture in SharePoint Online by using SharePoint hosted app, via JavaScript or jQuery? How do you solve it?

1 Answer 1

2

html:

 <input id="uploadInput" type="file" />

javascript:

        var fileInput = $('#uploadInput');

        for (var i = 0; i < fileInput[0].files.length; i++) {
            var file = fileInput[0].files[i];
            processprofilepic(file, '');
        }

        function processprofilepic(fileInput) {
            var reader = new FileReader();
            reader.onload = function (result) {
                var fileName = '',
                 libraryName = '',
                 fileData = '';

                var byteArray = new Uint8Array(result.target.result)
                for (var i = 0; i < byteArray.byteLength; i++) {
                    fileData += String.fromCharCode(byteArray[i])
                }

                // once we have the file perform the actual upload
                console.log("filename "+fileName);
                setprofilepic(fileData);

            };
            reader.readAsArrayBuffer(fileInput);
        }


        function setprofilepic(fileData) {


            url = shptService.appWebUrl + "/_api/SP.UserProfiles.PeopleManager/SetMyProfilePicture";


            // use the request executor (cross domain library) to perform the upload
            var reqExecutor = new SP.RequestExecutor(shptService.appWebUrl);
            reqExecutor.executeAsync({
                url: url,
                method: "POST",
                headers: {
                    "Accept": "application/json; odata=verbose",
                    "X-RequestDigest": fDigest
                },
                contentType: "application/json;odata=verbose",
                binaryStringRequestBody: true,
                body: fileData,
                success: function (x, y, z) {
                    alert("Success! Your file was uploaded to SharePoint.");
                },
                error: function (x, y, z) {
                    alert("Oooooops... it looks like something went wrong uploading your file.");
                }
            });
        }
6
  • I get an error when i trying to run your code :/ "Unable to retrieve the property files for a reference that is undefined or null" i < fileInput[0].files.length Oct 19, 2015 at 9:30
  • where is this error pointing on? or check the console for which line is the error.!
    – Looytawon
    Oct 19, 2015 at 9:58
  • no there was no error...thanks for your solution :) Oct 19, 2015 at 10:10
  • Good Cheers! :)
    – Looytawon
    Oct 19, 2015 at 10:12
  • there are no save button? Oct 19, 2015 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.