Working with list item attachments is not the best option, but it makes sense at certain points. For example it is a good place to store a pdf-version of your list item or other additional information to the listitem.
If you add an attachment to the list, SharePoint stores the listitem and then tries to upload your attachment. If the attached file has an incorrect filename or characters which are not allowed, the file will not be attached, but the list item will be saved. That’s not so cool, if you’re running workflows on your list.
One possibility is to validate the file name before the save event occurs. I found the script in this post.
[sourcecode language=”csharp”]
[/sourcecode]
This is helpfully for validating the filename of the file itself, but what if you want to check if the filename was already used by another attached file. In SharePoint you cannot add two files as attachment with the same filename. I found this post which explains it really good and also provides a solution by using the following code which i copied here (thanks to the author!)
[sourcecode language=”csharp”]
$(document).ready(attachEventHandlers);
function attachEventHandlers() {
// override the default event handler with our custom method
$(‘#attachOKbutton’).attr(“onclick”, “onAttachOKbuttonClicked()”);
}
function onAttachOKbuttonClicked() {
// get the name of the file last attached to the item
var newFilePath = $(‘#attachmentsOnClient’).find(‘input’).last().val();
// get the file name from the file path as described at
// http://stackoverflow.com/questions/423376/how-to-get-the-file-name-from-a-full-path-using-javascript
// TrimWhiteSpaces is a js method of SharePoint to filter out special characters from the file name
var newFileName = TrimWhiteSpaces(newFilePath).replace(/^.*[\\\/]/, ”);
var foundDuplication = false;
$(‘#idAttachmentsTable’).find(‘tbody’).find(‘tr’).each(function () {
var existingFileName = $(this).find(‘.ms-vb’).find(‘a’).text();
// if the existingFileName is empty then the attachment was uploaded in this session
// that is, it is not saved yet
if (existingFileName == ”) {
var existingFilePath = $(this).find(‘.ms-vb’).find(‘span’).text();
existingFileName = existingFilePath.replace(/^.*[\\\/]/, ”);
}
if (newFileName == existingFileName) {
foundDuplication = true;
return false;
}
});
if (foundDuplication) {
alert(“A file with name ‘” + newFileName + “‘ is already attached to this item.”);
}
else {
// call the OkAttach js method of SharePoint
// this is the method that is originally called by uploading attachments
OkAttach();
}
}
[/sourcecode]
Now the user gets a message that the attached file with its filename already exists and that he should use another filename for attaching. The item will not be saved so if there is an workflow which needs the attachments it won’t fire before the file is attached correctly.
Leave a Reply