Fetching file size using CAML query in Javascript client object model

Hi,
I am using the Javascript client object model to retrieve contents of a document library.
I have a document library, which contains a folder "Folder1" . "Folder1" has a zip file. I would like to get the file size of the zip file.
I have tried the below code, but not sure, how to fetch the file size.
function FetchImage() {
var clientcontext = new SP.ClientContext.get_current();
var oweb = clientcontext.get_web();
var olibrary = oweb.get_lists().getByTitle(DocLibrary);
var query = new SP.CamlQuery();
query.set_folderServerRelativeUrl("Lists/DocLibrary/folder1/");
folder = olibrary.getItems(query);
clientcontext.load(folder, 'Include(Title,ContentType, FileLeafRef,FileDirRef,File)');
clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderDataOnSuccess), Function.createDelegate(this, this.RenderDataOnFailure));
function RenderDataOnSuccess() {
var ListEnumerator = this.folder.getEnumerator();
while (ListEnumerator.moveNext()) {
var currentItem = ListEnumerator.get_current();
if (_contentType.get_name() != "Folder") {
var File = currentItem.get_file();
if (File != null) {
// Fetch file size
How to fetch the file size?
Thanks

<script>
function getSize()
        var myFSO = new ActiveXObject("Scripting.FileSystemObject");
        var filepath = document.upload.file.value;
        var thefile = myFSO.getFile(filepath);
        var size = thefile.size;
        alert(size + " bytes");
</script>
http://social.msdn.microsoft.com/Forums/en-US/e5d2ff3d-01c7-4cc0-a081-29a4dfbb0fad/getting-the-sharepoint-list-attachment-size-using-javascript?forum=sharepointcustomizationlegacy

Similar Messages

  • CAML Query to get specific item in folder based on dropdown value using Javascript client object model

    Hi,
    I am using the Javascript Client object model.
    I have a custom list and a custom document library.
    Custom list contains 2 columns - dlName , dlValue
    The document library contains 2 folders - "folder1" ,  "folder2" and contains some images.
    The image name starts with the "dlValue" available in the custom list
    I am using a visual webpart and using javascript client object model.
    I am trying to achieve the below functionality:
    1) Load a dropdown with the custom list.
    2) set the image based on the value in dropdown.
    I have achieved the first option, I have set the dropdown, but not sure how to query the folder and set the image.
    Below is the code i have used so far:
    //In Visual webpart
    <select id="ddlTest" >
    </select>
    <br/>
    <div id="PreviewLayer">
    <img id="imgPlaceHolder" runat="server" alt="Image" title="imgPlaceHolder" src=" " />
    </div>
    // In Javascript file
    function RenderHtmlOnSuccess() {
    var ddlTest = this.document.getElementById("ddlTest");
    ddlTest.options.length = 0;
    var enumerator = this.customListItems.getEnumerator();
    while (enumerator.moveNext()) {
    var currentItem = enumerator.get_current();
    var dropdownValue = currentItem.get_item("dlValue");
    ddlTest.options[ddlTest.options.length] = new Option(currentItem.get_item("dlName"), dropdownValue);
    setImage(dropdownValue); // Not sure how to query the folder and set the image based on value.
    // Also if dropdown value is changed, corresponding image should be shown
    How to query the folder and based on dropdown value, show the image? Also, how to handle the dropdown value change?
    Thanks

    Hi,
    Here are two links for your reference:
    Example of how to Get Files from a Folder using Ecmascript \ Javascript client object model in SharePoint 2010
    http://sharepointmantra.wordpress.com/2013/10/19/example-of-how-to-get-files-from-a-folder-using-ecmascript-javascript-client-object-model-in-sharepoint-2010/
    SP2010 JSOM Client Object Model: How to get all documents in libraries including all folders recursively
    http://sharepoint.stackexchange.com/questions/70185/sp2010-jsom-client-object-model-how-to-get-all-documents-in-libraries-including
    In SharePoint 2013, we can also use REST API to achieve it.
    http://msdn.microsoft.com/en-us/magazine/dn198245.aspx
    Thanks,
    Dennis Guo
    TechNet Community Support
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact
    [email protected]
    Dennis Guo
    TechNet Community Support

  • How can I get an item and it's attachments from the current list using SP's JavaScript Client Object Model on newform.aspx?

    I only recently learned/read about SharePoint's JavaScript Client Object Model. I'm reading online trying to figure this out but not having much luck.
    On newform.aspx (and dispform.aspx) I want to get the
    current list,
    the last item created, and it's attachments. I now the CAML query I need to get the last item created, but first I have to get the current list and I am not sure how to do that.
    I tried this but it returns null:
    SP.ListOperation.Selection.getSelectedList()

    Hi,
    For your issue, you can get the list name from the new form url and retrieve the list last created item :
    https://social.msdn.microsoft.com/Forums/office/en-US/b90a64f8-2255-41b0-9d91-78335dd4a4cf/get-list-name-from-list-url-through-javascript?forum=sharepointdevelopmentprevious
    http://msdn.microsoft.com/en-us/library/office/hh185007(v=office.14).aspx
    Best Regards,
    Eric
    Eric Tao
    TechNet Community Support

  • SharePoint 2013 implement simple logout button which do not redirect to default sign out page using JavaScript client object model

    I am using windows authentication in my web application.
    My requirement is to implement a sign out button which will sign out the user without having him to close the browser and application should not ask him to login again.
    I tried following two options:
     1. Redirecting the user to default signout.aspx page " /_layouts/15/SignOut.aspx "
     2. Using "Sign In as a different user" URL " /_layouts/15/closeConnection.aspx?loginasanotheruser=true "
    In first case, user is redirected to default sign out page but he can press "Go Back to Site" link to revisit the site. Another major issue is that the user has to close the browser to sign out from the application completely, which is not desirable
    in my project requirement.
    In second case, the the current user is signed out of the application but if the user has saved the password in browser, he gets signed in automatically to the application.
    I also came across the solution where we replace the default sign out page with a custom sign out page, but I am not sure whether it can be implemented using JavaScript Client Object Model of SharePoint.

    Hi 
    I'm basically looking for the exact answer for the query.
    Meanwhile you need to go through the link mentioned below in order to understand how to do it.
    Debugging and Logging Capabilities in SharePoint 2010
    Indul Hassan
    Microsoft Community Contributor
    http://www.indulhassan.com
    You Snooze.. You Lose !!

  • Get current item id using JavaScript Client Object Model

    I have a client query that query SharePoint list Items. Lets say it is a document library. I need to get the list item id of each. 
    I can query the Title of the document using this syntax.
    ctx.CurrentItem['Title']
    But when I try 
    ctx.CurrentItem['ID']
    for list item ID, it does not give a value. How can I solve this?

    Hi Malin,
    If you're using the JavaScript Client Object Model, try using the SPListItem.get_item('key') method as in the example below:
    <script>
    ExecuteOrDelayUntilScriptLoaded(function(){
    var arrIds = [];
    var clientContext = new SP.ClientContext();
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query></Query></View>');
    var items = clientContext.get_web().get_lists().getByTitle("Your List Title Here").getItems(camlQuery);
    clientContext.load(items);
    clientContext.executeQueryAsync(Function.createDelegate(this,function(){
    var itemEnumerator = items.getEnumerator();
    while(itemEnumerator.moveNext()){
    var itemId = itemEnumerator.get_current().get_item('ID');
    arrIds.push(itemId);
    alert(arrIds);
    }), Function.createDelegate(this, function(){
    alert("something went wrong");
    },"SP.js");
    </script>

  • Add multiple people using Javascript Client Object Model

    I am trying to add multiple people to a SP column of type Person/Group i.e. people picker. I am able
    to add one successfully using their userId, but HAVE no clue how to do that for multiple people. Here is the code for one user:
    function UserDrop(e, toElement, listGuid, columnName) {
    //EcmaScript Client Object Model
    var ctx = new SP.ClientContext.get_current();
    var list = ctx.get_web().get_lists().getById(listGuid);
    var item = list.getItemById(elementId);
    //columnName is of type person/group and I am adding user //whose userId is 7
    item.set_item(columnName, 7);
    item.update();
    // asynchronous call
    ctx.executeQueryAsync(
    function () { toElement.innerHTML = userLinkHtml; },
    function () {alert ("Error")}
    return false;
    This works great and I can add user whose userId is 7, however I want to add multiple people like let's say users of user Ids 7 and 8. 
    Any ideas or help will be greatly appreciated. 
    There is a thread on this one but that's from .net COM which could accessed here: http://social.msdn.microsoft.com/Forums/en-US/sharepoint2010general/thread/5183e87c-ee1d-4594-9492-0dfdf6616cce
    7929

    Hi ,
    Can somebody let me know how the same(assigning the array values to lookup value field) can be achieved with multi-select lookup value. SP.FieldLookUpValue do not have any such methods like fromUser. Please help. Please find my code block below
    clientContext = new SP.ClientContext.get_current();
    if (this.clientContext != undefined && clientContext != null) {
    var webSite = clientContext.get_web();
    oList = webSite.get_lists().getByTitle("Add New User");
    $.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
    var itemid = parseInt($.urlParam('ID'));
    var item = oList.getItemById(itemid);
    var users = new Array();
    users.push(SP.FieldLookupValue.set_lookupId(1));
    users.push(SP.FieldLookupValue.set_lookupId(2));
    item.set_item('Responsibility', users);
    item.update();
    clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
    also i cant use managed client object model.. so pls let me know how to achieve the same using javascript client object model
    Ranjani.R

  • Add attachments to List Item using JavaScript Client object model in SP2010

    Hi All ,
    I have created custom form for submitng data in list using javascript client object model/jquery .
    Now I want to add option to uplaod multiple attachments to that list item also .
    Is there option with client object model for uplaoding attachment.
    Thanks
    M
    Manesh G

    Can you try this and let me know
    using (SPSite _site = new SPSite(SPContext.Current.Site.Url))
        using (SPWeb _web = _site.OpenWeb())
         //Let's suppose your Item Id is 1
         int ItemId = 1;
         SPList  oList = _web.Lists["EmployeeList"];
         SPListItem  _item = oList.GetItemById(ItemId);
         if (FileUpload1.HasFile)
               _web.AllowUnsafeUpdates = true;
              Stream fs = FileUpload1.PostedFile.InputStream;
              byte[] _bytes = new byte[fs.Length];
              fs.Position= 0;
              fs.Read(_bytes, 0, (int)fs.Length);
              fs.Close();
              fs.Dispose();
              _item.Attachments.Add(FileUpload1.PostedFile.FileName, _bytes);
              _item.Update();
              _web.AllowUnsafeUpdates = false;

  • Read versions of comments field using javascript client object model

    Hi,
     Does someone knows how to Read versions  of comments field in 'tasks' list using javascript client object model?
    Thanks
    Manvir

    Hi,
    According to your description, I know you want to read versions of comments field.
    We can use the
    SPServices to achieve it. The below code for your reference:
    $().SPServices({
    operation: "GetVersionCollection",
    async: false,
    strlistID: "tester",
    strlistItemID: 1,
    strFieldName: "comments",
    completefunc: function (xData, Status) {
    $(xData.responseText).find("Version").each(function(i) {
    console.log("Name: " + $(this).attr("Information") + " Modified: " + $(this).attr("Modified"));
    More information:
    http://spservices.codeplex.com/releases/view/81401
    Best Regards,
    Dennis Guo

  • Rename a File in a SharePoint document library through Client object model

    Hi,
    How  to Rename a File in a SharePoint document library through Client object model?
    Thanks
    Poomani Sankaran

    Hi,
    According to your description, you want to rename file in the document library using SharePoint Client Object Model.
    Here is a code snippet works well in my environment for your reference:
    static void Main(string[] args)
    string url = "http://sp2013sps/sites/test/";
    ClientContext clientContext = new ClientContext(url);
    Microsoft.SharePoint.Client.List spList = clientContext.Web.Lists.GetByTitle("Documents");
    clientContext.Load(spList);
    clientContext.ExecuteQuery();
    if (spList != null && spList.ItemCount > 0)
    Microsoft.SharePoint.Client.CamlQuery camlQuery = new CamlQuery();
    camlQuery.ViewXml =@"<View> <Query> <Where><Eq><FieldRef Name='LinkFilenameNoMenu' /><Value Type='Computed'>New Microsoft Word Document.docx </Value></Eq></Where> </Query> <ViewFields><FieldRef Name='Title' /></ViewFields> </View>";
    ListItemCollection listItems = spList.GetItems(camlQuery);
    clientContext.Load(listItems);
    clientContext.ExecuteQuery();
    listItems[0]["Title"] = "word.docx";
    listItems[0]["FileLeafRef"] = "word.docx";
    listItems[0].Update();
    clientContext.ExecuteQuery();
    More information about SharePoint Client Object Model:
    http://msdn.microsoft.com/en-us/library/office/ee537247(v=office.14).aspx
    http://www.codeproject.com/Articles/399156/SharePoint-Client-Object-Model-Introduction
    http://www.learningsharepoint.com/2010/07/12/programmatically-upload-document-using-client-object-model-sharepoint-2010/
    Best regards

  • Getfilebyserverrelativeurl not working in Javascript client object model

    Hi,
    I am using the "getfilebyserverrelativeurl" to verify if the file exists. But it does not seem to work.
    I am using Javascript client object model.
    Below is the code used:
    //ImageName = "test1.jpg" . This file does not exist in the below location
    var url = oweb.get_url() + "/Lists/LibraryName/folder1/" + ImageName;
    try {
    var fileUrl = oweb.get_serverRelativeUrl() + "/Lists/LibraryName/folder1/" + ImageName;
    oweb.getFileByServerRelativeUrl(fileUrl);
    window.location = url;
    catch (e) {
    alert("File does not exist.");
    I am not getting any errors in javascript, but the alert is not showing up.
    The file does not exist in the folder, so I am expecting the alert, but in-turn it redirects to "Page not found" OOB page.
    How to fix this?
    Thanks

    Hello,
    I see a few odd things with that code.
    Try it with the following changes and see if it makes a difference:
    // declared globally
    var fileName= "";
    var fileurl = "";
    function downloadImage(){
    fileName = "image1.zip";
    fileurl = SP.ClientContext.get_current().get_url() + "/LibraryName/foldername/" + fileName;
    var clientcontext = new SP.ClientContext.get_current()
    var oweb = clientcontext.get_web();
    var ofile = oweb.getFileByServerRelativeUrl(fileurl);
    clientcontext.load(ofile);
    clientcontext.executeQueryAsync(Function.createDelegate(this, this.RenderDownloadfilesOnSuccess), Function.createDelegate(this, this.RenderDownloadfilesOnFailure));
    function RenderDownloadfilesOnSuccess() {
    window.location = fileurl;
    function RenderDownloadfilesOnFailure(sender, args) {
    alert(fileName + " does not exist.");
    Which version of Internet Explorer are you using for debugging? The F12 developer tools will allow you to debug JavaScript and "step out" of executing JavaScript code so you can trace the problem back to where it originates in your own code
    instead of debugging the resulting errors that crop up in the built-in stuff (like MicrosoftAjax.js)

  • Enable anonymous access for Javascript Client Object Model

    In SharePoint 2010 it was possible to use the Javascript Client Object Model with anonymous access enabled by removing "GetItems" from the ClientCallableSettings.AnonymousRestrictedTypes.
    In SharePoint 2013 however, it seems that an extra security barrier has been implemented. Trying to use the Javascript Client Object Model results in the following message: "Access denied. You do not have permission to perform this action or access this
    resource."
    After this I went on to do a little research, and it appears that Javascript Client Object Model actually relies on the REST API (please correct me if I'm mistaken), and the REST API also doesn't seem to work as an anonymous user.
    So I'm in the dark here. I can't imagine that SharePoint 2013 (so heavily relying on the client object model) can't be used with anonymous access. I've also found very little documentation on anonymous access in combination with SharePoint 2013.
    So, how do I enable the Javascript Client Object Model to be used with anonymous access enabled?
    P.S. Needless to say, my web application is enabled for anonymous access and so is my site collection.

    There are really 4 things you need to do to enable anonymous access:
    1. In web application level, enable anonymous.
    2. In site collection level, make sure anonymous access Entire Website.
    3. In Web level, set Full Permission Masks, till here, you're able to anonymously access REST APIs.
    # Enable Anonymous access
    $web = Get-SPWeb $url
    if($web -ne $null)
        Write-Host
        Write-Host -ForegroundColor Yellow "Enabling Anonymous access on:" $web.Url
        Write-Host
        $web.AnonymousState = "On"
        Write-Host -ForegroundColor Yellow "AnonymousState set to:" $web.AnonymousState
        $web.AnonymousPermMask64 = "FullMask"
        Write-Host -ForegroundColor Yellow "AnonymousPermMask64 set to:" $web.AnonymousPermMask64
        $web.Update()
        Write-Host
    Below are the things to enable anonymous client object model APIs:
    4. In web application level, Require Use Remote Interfaces Permission - uncheck it.
    5. In web application level, Anonymous Restricted Types, remove all of them:
    $app.ClientCallableSettings.AnonymousRestrictedTypes.RemoveAll()

  • How to execute XML batch commands using SharePoint Web services or Client Object Model

    Hi,
    I have a requirement to execute some batch commands to update SharePoint View Style, how can i do it using SharePoint webservices or SharePoint Client Object model.
          I need to execute the following Batch command over a particular web.
    <Method ID="UpdateView">
      <SetVar Name="Cmd">UpdateView</SetVar>
      <SetList Scope="Request">{GUID of List}</SetList>
      <SetVar Name="View">{GUID of View}</SetVar>  
      <SetVar Name="ViewStyle">6</SetVar>
      <SetVar Name="RowLimit">100</SetVar>
      <SetVar Name="Paged">TRUE</SetVar>
    </Method>

    Hi
    I tried it already... But UpdateView Method in the Views.asmx and Lists.asmx, both are not supporting for updating the style of the view (like Boxed, Newsletter...).
    If you have any code sample which will do this job with any of the SharePoint web services, please share it..

  • Accessing active directory with javascript client object model

    Hello All,
    my requirement is to get user profile "picture" from
    active directory of my org. to my sharepoint 2013 intranet site via
    java script client object model programming.
    I am successful in retrieving user details (including pics) from user profile services using SP.UserProfile.js but it will show only user who are added in SharePoint groups. But, I need all company users (10,000+ user's) data like name, dept, photo etc.
    If the solution is not feasible with JSOM, please provide any alternative.
    Pls. assist.
    Thanks, Chintan

    You can import profile from AD directly to sharepoint and use it
    Check below:
    http://blogs.technet.com/b/harmeetw/archive/2011/09/10/importing-thumbnail-photos-from-ad-active-directory-into-sharepoint-2010.aspx
    Once imported you need to run below:
    Update-SPProfilePhotoStore -CreateThumbnailsForImportedPhotos 1 -MySiteHostLocation
    http://<YourServerName>/my
    The cmdlet was introduced in this fix:
    http://support.microsoft.com/kb/2394320  (14.0.5128.5000)
    http://blogs.technet.com/b/lukeb/archive/2013/01/04/sharepoint-import-a-picture-from-ad-for-the-user-profile.aspx

  • Is it possible to create a new wiki page in wiki document library via Javascript Client Object Model?

    I can find example using managed code, but I can get it translated to javascript code that I can use.
    For example, this in managed code:
    using
    (SPSite
    site = new
    SPSite("http://sharepoint"))
      SPWeb
    rootWeb = site.RootWeb;
      SPList
    wiki = rootWeb.Lists["MyWiki"];
      SPFolder
    rootFolder = wiki.RootFolder;
      SPFile
    wikiPage = rootFolder.Files.Add(String.Format("{0}/{1}",
    rootFolder, "My
    Wiki Page.aspx"),
    SPTemplateFileType.WikiPage);
    When
    I try to change that to javascript, I get a 'cannot find rootfolder'....
    This
    is what I have so far:
    var pageName = "/digitalmerch/PageNotes/" + $('input[title="Page Name"]').val() + ".aspx";
    //Get the current client context - creating the batch
    context = SP.ClientContext.get_current(); 
    site = context.get_web(); 
    wiki = site.get_lists('PageNotes');
    rootFolder = wiki.get_rootFolder();
    wikiPage = rootFolder.get_files().AddTemplateFile(pageName), TemplateFileType.WikiPage);
    context.load(wikiPage);
      context.executeQueryAsync(CreatePage2Succeeded, CreatePage2Failed);
    But I obviously haven't translated this into javascript correctly -  the .get_rootFolder is undefined, and so the rootFolder.get_files().... is wrong as well.
    Any hints?
    Robin

    Not specifically, this is on a standard list NewForm.aspx page - it should already be there. The code is in the PreSaveAction function, so by that time sp.js should be fully loaded on the page - I don't wait for it or use a ExecuteOrDelayUntilScriptLoaded(xxxx,"sp.js");
    I know this is a syntax error somewhere. Also, all my objects are declared as global, so it shouldn't be anything like that..
    And I see a typo above that I've fixed:
    wikiPage = rootFolder.get_files().AddTemplateFile(pageName), TemplateFileType.WikiPage);
    is actually
    wikiPage = rootFolder.get_files().AddTemplateFile(pageName, TemplateFileType.WikiPage);
    but that didn't help. I still get:
    Object does not support get_rootFolder.
    I've also tried splitting that part into the execution functions, making sure I load 'RootFolder' into the context, but that doesn't work either.
    Robin

  • Retrieving RoleAssignments via Javascript Client Object Model

    I am so stuck on the structure of this, I'm beating my head against a wall. I get the basics, and I understand the .load() that only bring in base values and if you have a property that's a collection you have to define it as well, but I can't get the syntax
    right on rolling through the role assigments to get the name and type of permissions.
    I start with 
    ctx = new SP.ClientContext('/');
    web = ctx.get_web();
    list = web.get_lists().getByTitle('Links');
    ctx.load(list, 'RoleAssignments');
    //execute query
    ctx.executeQueryAsync(GetListItemIdSuccess, GetListItemIdFail);
    and yes, I'm doing this after sp.js load.
    My GetListItemIdSuccess is where I want to run through the role assignments and list them out.
    function GetListItemIdSuccess(sender, args) {
    var collra = list.get_roleAssignments();
    alert(collra.get_count());
    The alert shows me there are 18 assignments, and that's correct, there are 18 groups and individuals given access. But I've tried running though it with .getEnumerator(), trying to access it as an array, etc, but all I get is either 'undefined' or the 'it
    wasn't brought back in the query it hasn't been initialized. I'm not that strong of a javascript programmer to figure out the syntax. I've been using a debugger to look at the objects and their methods/properties, but I think they're just showing me basic
    object properties.
    All the blogs and examples I've read are adding to these collections, not just reading them. And if they're displaying properties, they're always simple string properties not running through collections.
    Help?
    Robin

    Check if this helps.
    http://www.codeproject.com/Articles/678653/How-to-check-user-permission-for-the-web-list-or-S
    http://sharepoint.stackexchange.com/questions/80427/how-to-check-permissions-of-a-page-youre-not-currently-on-with-javascript
    var siteUrl = '/mysites/MySiteCollections';
    function sharePointReady()
    var clientContext = new SP.ClientContext(siteUrl);
    var oWebsite = clientContext.get_web();
    this._currentUser = oWebsite.get_currentUser();
    context.load(this._currentUser);
    context.load(web,'EffectiveBasePermissions');
    context.executeQueryAsync(Function.createDelegate(this,this.onSuccessMethod),
    Function.createDelegate(this, this.onFailureMethod));
    function onSuccessMethod(sender, args)
    if (website.get_effectiveBasePermissions().has(SP.PermissionKind.editListItems)) {
    alert('Nice, edit list permissions!');
    else {
    alert('Boo, no edit list permissions!');
    function onRequestFailed(sender, args)
    console.log('Error: ' + args.get_message());
    alert('Request failed: ' + args.get_message() + '\n'+ args.get_stackTrace());
    http://stackoverflow.com/questions/15935101/get-user-group-permissions-for-list-using-javascriptecmascript
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/f21ad6b1-445a-497d-a286-d3ba8c2928a6/how-to-get-the-current-user-permission-level-on-a-list-item-with-ecmascript?forum=sharepointgeneralprevious

Maybe you are looking for