Monday 7 October 2013

Upload images to SharePoint library when imputting a Picture field


Issue
In SharePoint it is very common that you use “Hyperlink or Picture” column on lists and libraries to represent a picture. Unfortunately within the default input form you can only type an URL. If you need to upload image to a SharePoint library, it will need to be done as a separate step.

Workaround
One approach involves injecting JavaScript to popup a dialog for user to upload pictures when inputting the form. In my case I’ve created a custom list with just a Title field and a Picture column called “Picture”. Open NewForm.aspx, insert a content editor and paste the following script over, assuming you already have jQuery reference ready, i.e. in your master page.





<script type="text/javascript">
    $('document').ready(function () {
        $('tr[id^=Picture] td:last').append('<br/><button style="background-color:pink;" type="button" id="btnUpload">Upload Picture</button>');

         $('#btnUpload').on('click', function () {
            SP.UI.ModalDialog.showModalDialog({
                url: L_Menu_BaseUrl + "/_layouts/RteUploadDialog.aspx?LCID=1033&Dialog=UploadImage&UseDivDialog=true",
                title: "Upload a picture",
                dialogReturnValueCallback: function (result, value) {

                    if (result == SP.UI.DialogResult.OK) {
                        $('input[title=Picture]').val($(value).attr('src'));
                    }

                }

            });

        });

    });

</script>
 
 

 
 
 

 
 
The return value from RteUploadDialog.aspx is an img tag. Thus we parse it to extract the src attribute and use it to populate the URL value of the Picture column.