I'm moving files with spservices (the jquery plugin) and was wondering if there was a good way to check to see if a file with the same name already exists so I can append an underscore or something random (a WF runs to rename after the copy anyway) before copying there since it seems to do an automatic overwrite.
2 Answers
Since you mentioned SPServices, below is demonstrated how to query list item by file name using GetListItems operation:
function fileExists(webUrl,listName,fileName,result) {
$().SPServices({
operation: "GetListItems",
webURL: webUrl,
listName: listName,
CAMLQuery: "<Query><Where><Eq><FieldRef Name='FileLeafRef' /><Value Type='File'>" + fileName + "</Value></Eq></Where></Query>",
completefunc: function (xData, Status) {
var itemCount = $(xData.responseXML).SPFilterNode("rs:data").attr("ItemCount");
result((parseInt(itemCount) > 0));
}
});
}
//Usage
fileExists('https://contoso.sharepoint.com','Documents','Agreement.docx',function(found){
if (found) console.log('File exists');
});
Without knowing more information about your code, it's hard to make a suggestion. But what I would do is create a query to ListData.svc with the following filter:
var queryString = "?$filter=Name eq '" + provisdionalName + "'";
var listUrl = "_vti_bin/Listdata.svc/YourList/$count" + queryString;
$.ajax({
type: "GET",
url: listUrl,
}).done(function (data, textStatus, jqXHR) {
//data will have just the value of a number
//that you can parse.
var numberOfDocs = parseInt(data);
if(numberOfDocus !== 0){
//change the name
}
}).fail(function (jqXHR, textStatus, errorThrown) {
//Handle your error
});
Be aware that there are two properties that might be applicable to what you need to check
Name: Ordering Pre-Production Kits.pdf
Title: Ordering Pre-Production Kits
The Title is what is displayed in the UI by default, I believe. The Name attribute is the file name. I bring this up because these can be completely different, not just one having the file extension and the other not.
Other than that, there may be an option in SPServices to do this automatically, but I'm not sure. The benefit of this is that it would give your more liberty in what sort of prefix you could use.
-
2I've used the list based service a few times to get the item count because it does that for you straight away with the $count option instead of having to the look for it in the XML and parse it out.Eric Alexander– Eric Alexander2014-03-24 23:39:17 +00:00Commented Mar 24, 2014 at 23:39
-
I use
$countfor building dashboards a lot. Easy to get the number of items added in last 30 days, etc.Robert Kaucher– Robert Kaucher2014-03-24 23:47:06 +00:00Commented Mar 24, 2014 at 23:47