Header

Showing posts with label File Upload. Show all posts
Showing posts with label File Upload. Show all posts

Tuesday, 2 May 2023

File upload and overwrite into the SharePoint library using JavaScript

 Hi Friends,

We will see how we can upload file into the SharPoint library and also overwrite, if the file is present into the library.

We can use the below code to upload the file into the SharePoint document library.

Also we can overwrite the file if already present into the Document library.

By default, it does not allow to overwrite the file but through the code we can set overwrite true.

set_overwrite(true);

  <script language="javascript" type="text/javascript">

        var fileInput;
        $(document).ready(function () {

                fileInput = $("#getFile");
                SP.SOD.executeFunc('sp.js', 'SP.ClientContext', registerClick);

            });

        function registerClick() {
            //Register File Upload Click Event   
            $("#addFileButton").click(readFile);
        }

        var arrayBuffer;

        function readFile() {

            //Get File Input Control and read the file name  
            var element = document.getElementById("getFile");
            var file = element.files[0];
            var parts = element.value.split("\\");
            var fileName = parts[parts.length - 1];

            //Read File contents using file reader  

            var reader = new FileReader();
            reader.onload = function (e) {
                uploadFile(e.target.result, fileName);
            }
            reader.onerror = function (e) {
                alert(e.target.error);
            }

            reader.readAsArrayBuffer(file);
        }

        var attachmentFiles;

        function uploadFile(arrayBuffer, fileName) {
            //Get Client Context,Web and List object.  
            var clientContext = new SP.ClientContext();
            var oWeb = clientContext.get_web();
            var oList = oWeb.get_lists().getByTitle('Documents');

            //Convert the file contents into base64 data  
            var bytes = new Uint8Array(arrayBuffer);
            var i, length, out = '';
            for (i = 0, length = bytes.length; i < length; i += 1) {
                out += String.fromCharCode(bytes[i]);
            }
            var base64 = btoa(out);

            //Create FileCreationInformation object using the read file data  
            var createInfo = new SP.FileCreationInformation();
            createInfo.set_content(base64);
            createInfo.set_overwrite(true);
            createInfo.set_url(fileName);

            //Add the file to the library  

            newFile = oList.get_rootFolder().get_files().add(createInfo);
            var myListItem = newFile.get_listItemAllFields();
            myListItem.set_item("PID", "33")

            //Load client context and execcute the batch  
            myListItem.update();
            clientContext.load(newFile);
            clientContext.executeQueryAsync(QuerySuccess, QueryFailure)
        }

        function QuerySuccess() {

            console.log('File Uploaded Successfully.');
            alert("File Uploaded Successfully.")
        }

        function QueryFailure(sender, args) {

            console.log('Request failed with error message - ' + args.get_message() + ' . Stack Trace - ' + args.get_stackTrace());
            alert("Request failed with error message - " + args.get_message() + " . Stack Trace - " + args.get_stackTrace());

        }


    </script>



Monday, 20 February 2012

How to upload image in Sharepoint Document

Hi Frnds,
Some time we need to upload one image for each pages in document library.
So i am uploading one -one image for each page and giving name for image is page name so it would be unique.
This is being stored in one document library.

  Dim spSite As SPSite = New SPSite("yoursite url")
            Dim _web As SPWeb = spSite.OpenWeb()
            Dim slist As SPList = _web.Lists("Content Images")
            Dim sPath As String = System.Web.HttpContext.Current.Request.Url.AbsolutePath
            Dim oInfo As System.IO.FileInfo = New System.IO.FileInfo(sPath)
            Dim sRet As String = HttpUtility.UrlDecode(oInfo.Name)
            Dim imageName As String = sRet.Substring(0, sRet.LastIndexOf("."))
            If FileUploadAttach.HasFile Then
                Dim fileExtension As String = FileUploadAttach.FileName.ToString.Substring(FileUploadAttach.FileName.ToString.LastIndexOf("."))

                imageName = imageName + fileExtension

                Dim destfile As SPFile = slist.RootFolder.Files.Add(slist.RootFolder.Url + "/" + imageName, FileUploadAttach.FileBytes, True)

                Dim item As SPListItem = destfile.Item
                item("Title") = FileUploadAttach.FileName.ToString
                item.Update()
            End If

Thanks and regards
Shailendra Kumar Singh