14 Oct

File Attachments for Custom Lists

You can enable any SharePoint List to attach files directly to each list item. Here I created a custom list called “Sample Reports” with only the default Title column, although other columns could be added to keep track of more information about the report. The paperclip on the left-hand side of the view is the Attachments column.
 

List view of a custom list with attachments enabled 

The attachments option is already available when you create a custom list, but you can enable it for any kind of list by going into List Settings > Advanced Settings and selecting the “Enable attachments” radio button.
*Tip: Please be aware that file attachments do not allow versioning; you must use a Lookup to a separate document library if you wish to keep a version history of the files.

 
Go into the List Settings to enable attachments for any list


Allow the User to attach a File

1. Drop the FileUpload control into the ASCX file. Along with the other form controls when adding an item, drop in the asp:FileUpload control. Be sure to add an OnClick event to the button.

2. Use an SPAttachmentCollection to retrieve the indicated file and assign it to the SPList item. Switch to Code View (F7). In the click event, create a new item with the AddItem() method. SPListItem objects have the Attachments property to which you can assign an SPAttachmentCollection. First check if the control has a file, then add it to the collection with two arguments: the file’s name and the file’s data as a byte array.

In my example, I only use one FileUpload control, but you can iterate through several FileUpload controls and allow the user to attach multiple files.

The Web part will look something like this once you deploy it and put it on a page.
 

The user will click the Browse button to upload a local item 

After clicking save, you can send the user to the list view. Clicking “View Properties” on the item will list hyperlinks to the item’s attachments.
 

Attachments are listed under the item


Retrieve Attached Files

What about programmatically creating hyperlinks to the attachments? The item[“Attachments”] field only contains a Boolean value indicating if the item has attachments or not. Just as you would expect, you would use the Attachments property of the item as an SPAttachmentCollection.

You can use the Count attribute of SPAttachmentCollection to find out how many attachments the item has. Each index of the array is the file name. The URL of the attachment is the URL of the SharePoint site + /Lists/(list-name)/Attachments/(item-id)/ + the file name.

Copyright © 2014 Keren Apura; Fruitful theme by fruitfulcode