Skip to content
Amal Hashim
All posts
Snippet

SharePoint Sandbox solution - Add an attachment to a list item

Upload an attachment to a list item from a sandboxed visual web part by opening the AttachFile.aspx page in a modal dialog.

Sandbox solutions and SharePoint Online have several limits, and file upload is one of the biggest. I needed a visual web part, packaged as a sandbox solution, that could attach documents to custom list items. After trying a few options, this worked.

For simplicity, a button opens a dialog where the user selects a document and uploads it.

User control

The script opens the SharePoint modal dialog on the URL held in a hidden field.

html
<script type="text/javascript">
    function callback() {
        alert('document uploaded');
    }

    function openPopup() {
        var elem = document.getElementById('<%= hdnURL.ClientID %>');
        var options = {
            url: elem.value,
            title: 'Modal Dialog',
            allowMaximize: false,
            showClose: true,
            width: 600,
            height: 500,
            dialogReturnValueCallback: callback
        }
        SP.UI.ModalDialog.showModalDialog(options);
        return false;
    }
</script>

<input type="button" value="Upload" id="btnUpload" runat="server" onclick="return openPopup();" disabled="disabled"/>
<input type="hidden" runat="server" id="hdnURL"/>

Code behind

Build the attachment URL by filling in the list ID and the item ID, then enable the button.

csharp
string urlFormat = "/_layouts/AttachFile.aspx?ListId={0}&ItemId={1}";
string url = string.Format(urlFormat, "{DC847F22-A785-42E5-9487-45419781B81B}", "1");
hdnURL.Value = url;
btnUpload.Disabled = false;

Scenario

  1. A user opens a custom list item that has your web part.
  2. They click Upload and the standard attach file dialog opens.
  3. They choose a document and confirm. The file is added as an attachment on that item.
  4. The callback runs and shows "document uploaded".