Search This Blog

Wednesday, August 28, 2019

Sharepoint 2013/2016 - JSOM Code for File Upload Max Limit >2MB File


//jqeyry path
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
        $(document).ready(function () {
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function () {
                init();
            });
        });

        function init() {
            $("#btnUploadFiles").click(function () {
                var files = $("#inputTypeFiles")[0].files;
                uploadFiles(files[0]); // uploading singe file
            });
        }

        function uploadFiles(uploadFileObj) {
            var fileName = uploadFileObj.name;
            var webUrl = _spPageContextInfo.webAbsoluteUrl;
            var documentLibrary = "Shared Documents";
           // var folderName = "Folder1";
            //var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/" + folderName;
            var targetUrl = _spPageContextInfo.webServerRelativeUrl + "/" + documentLibrary + "/";
            var url = webUrl + "/_api/Web/GetFolderByServerRelativeUrl(@target)/Files/add(overwrite=true, url='" + fileName + "')?@target='" + targetUrl + "'&$expand=ListItemAllFields,ListItemAllFields/MPListID,ListItemAllFields/DocumentNo,ListItemAllFields/DocRevNo,ListItemAllFields/Station";

            uploadFileToFolder(uploadFileObj, url, function (data) {
                var file = data.d;
                var updateObject = {
                    __metadata: {
                        type: file.ListItemAllFields.__metadata.type
                    },
                    MPListID: 1,//meta data column1
                    DocumentNo: 'Test Data',                  
                    DocRevNo: 'Test Data',    //meta data column2
                    Station: 'Test Data'    //meta data column2
                };
                url = webUrl + "/_api/Web/lists/getbytitle('" + documentLibrary + "')/items(" + file.ListItemAllFields.Id + ")";

                updateFileMetadata(url, updateObject, file, function (data) {
                    alert("File uploaded &amp;amp; meta data updation done successfully");
                }, function (data) {
                    alert("File upload done but meta data updating FAILED");
                });
            }, function (data) {
                alert("File uploading and meta data updating FAILED");
            });
        }

        function getFileBuffer(uploadFile) {
            var deferred = jQuery.Deferred();
            var reader = new FileReader();
            reader.onloadend = function (e) {
                deferred.resolve(e.target.result);
            }
            reader.onerror = function (e) {
                deferred.reject(e.target.error);
            }
            reader.readAsArrayBuffer(uploadFile);
            return deferred.promise();
        }

        function uploadFileToFolder(fileObj, url, success, failure) {
            var apiUrl = url;
            var getFile = getFileBuffer(fileObj);
            getFile.done(function (arrayBuffer) {
                $.ajax({
                    url: apiUrl,
                    type: "POST",
                    data: arrayBuffer,
                    processData: false,
                    async: false,
                    headers: {
                        "accept": "application/json;odata=verbose",
                        "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
                    },
                    success: function (data) {
                        success(data);
                    },
                    error: function (data) {
                        failure(data);
                    }
                });
            });
        }

        function updateFileMetadata(apiUrl, updateObject, file, success, failure) {
            $.ajax({
                url: apiUrl,
                type: "POST",
                async: false,
                data: JSON.stringify(updateObject),
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                    "Content-Type": "application/json;odata=verbose",
                    "X-Http-Method": "MERGE",
                    "IF-MATCH": file.ListItemAllFields.__metadata.etag,
                },
                success: function (data) {
                    success(data);
                },
                error: function (data) {
                    failure(data);
                }
            });
        }
    </script>

</head><body>
<div class="center">
    <input type="File" id="inputTypeFiles" />

    <br>
    <input type="button" id="btnUploadFiles" value="submit" Text="Upload" />
</div>   
</body>
</html>

Friday, August 16, 2019

SharePoint Client Context(c#) - Download Attachment to Drive Folder


using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using SP = Microsoft.SharePoint.Client;
namespace SPFileDownload
{
    class Program
    {
        static string WebAppUrl = ConfigurationManager.AppSettings["WebAppUrl"];
        static string siteUrl = ConfigurationManager.AppSettings["SiteUrl"];
        static string ListName = ConfigurationManager.AppSettings["ListName"];
        static void Main(string[] args)
        {
            using (SP.ClientContext clientContext = new SP.ClientContext(siteUrl))
            {
                Console.WriteLine("Please enter download folder path (for ex: C:\\Downloads\\) ");
                Console.Write("Input :");
                string folderpath = Console.ReadLine();
                DownlaodAllAttachmentFromList(clientContext, ListName, folderpath);
            }
        }
        private static void DownlaodAllAttachmentFromList(SP.ClientContext clientContext, string eMSListName,string folderPath)
        {
          
            try
            {             

                using (clientContext)
                {
                    SP.List spList = clientContext.Web.Lists.GetByTitle(ListName);
                    clientContext.Load(spList);
                    clientContext.ExecuteQuery();
                    int count = 0;
                    if (spList != null && spList.ItemCount > 0)
                    {
                        SP.CamlQuery camlQuery = new SP.CamlQuery();                      
                        camlQuery.ViewXml = "<View Scope=\"RecursiveAll\"></View><Query><Where><Eq><FieldRef Name='Status' /><Value Type='Text'>Published</Value></Eq></Where><OrderBy><FieldRef Name='Created' Ascending='False' /></OrderBy></Query>";
                        SP.ListItemCollection collListItem = spList.GetItems(camlQuery);
                        //SP.CamlQuery camlQuery = new SP.CamlQuery();
                        //camlQuery.ViewXml = "<View Scope=\"RecursiveAll\"></View>";
                        //SP.ListItemCollection collListItem = spList.GetItems(camlQuery);
                        clientContext.Load(collListItem);
                        clientContext.ExecuteQuery();
                        foreach (var item in collListItem)
                        {
                            if (Convert.ToString(item["Status"]) == "Published")
                            {                            
                                clientContext.Load(item.AttachmentFiles);
                                clientContext.ExecuteQuery();
                                if (item.AttachmentFiles.Count > 0)
                                {
                                    count = count + 1;
                                    foreach (var attachment in item.AttachmentFiles)
                                    {
                                       // DirectoryInfo dir = Directory.CreateDirectory(folderPath + item["ID"].ToString());
                                        DirectoryInfo dir = Directory.CreateDirectory(folderPath);
                                        FileInfo myFileinfo = new FileInfo(attachment.FileName);
                                        using (WebClient client1 = new WebClient())
                                        {
                                            client1.Headers["Accept"] = "/";
                                            client1.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
                                            client1.UseDefaultCredentials = true;
                                         //   client1.DownloadFile(WebAppUrl + attachment.ServerRelativeUrl, folderPath + item["ID"].ToString() + "/" + attachment.FileName);
                                            client1.DownloadFile(WebAppUrl + attachment.ServerRelativeUrl, folderPath  + "/" + attachment.FileName);
                                            Console.WriteLine("Downloading " +count.ToString() +" : " + attachment.FileName);
                                        }
                                    }
                                  
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogWriter log = new LogWriter("download failed." + ex.Message + ex.StackTrace);             
            }
         
        }
    }
}