zoukankan      html  css  js  c++  java
  • SPS中JSOM和SOAP 实现文件上传

    一、HTML控件

        <input type="file" id="upFile" style="300px;"/>
        <div id="fileDisplayArea">
        </div>
        <input type="button" value="Upload" onclick="CreateFile()" />
    View Code

    二、FileCreationInformation 方式

            var file;
            var newFile;
            var fileCreateInfo;
            function CreateFile() {
                // Ensure the HTML5 FileReader API is supported
                if (window.FileReader) {
                    input = document.getElementById("upFile");
                    if (input) {
                        file = input.files[0];
                        fr = new FileReader();
                        fr.onload = receivedBinary;
                        fr.readAsDataURL(file);
                    }
                }
                else {
                    alert("The HTML5 FileSystem APIs are not fully supported in this browser.");
                }
            }
    
            // Callback function for onload event of FileReader
            function receivedBinary() {
    
                var clientContext = new SP.ClientContext.get_current();
                var oWebsite = clientContext.get_web();
                clientContext.load(oWebsite);
                var list = oWebsite.get_lists().getByTitle("Apptexfiles");
    
                fileCreateInfo = new SP.FileCreationInformation();
                fileCreateInfo.set_url(file.name);
                fileCreateInfo.set_overwrite(true);
                fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
    
                // Read the binary contents of the base 64 data URL into a Uint8Array
                // Append the contents of this array to the SP.FileCreationInformation
                var arr = convertDataURIToBinary(this.result);
                for (var i = 0; i < arr.length; ++i) {
                    fileCreateInfo.get_content().append(arr[i]);
                }
    
                // Upload the file to the root folder of the document library
                newFile = list.get_rootFolder().get_files().add(fileCreateInfo);
    
                clientContext.load(newFile, 'ListItemAllFields'); //'Include(ID, Title, FileRef)'
                clientContext.executeQueryAsync(onSuccess, onFailure);
            }
    
            function onSuccess() {
                // File successfully uploaded
                alert("Success!");
            }
    
            function onFailure() {
                // Error occurred
                alert("Request failed: " + arguments[1].get_message());
                console.log("Request failed: " + arguments[1].get_message());
            }
    
            // Utility function to remove base64 URL prefix and store base64-encoded string in a Uint8Array
            // Courtesy: https://gist.github.com/borismus/1032746
            function convertDataURIToBinary(dataURI) {
                var BASE64_MARKER = ';base64,';
                var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
                var base64 = dataURI.substring(base64Index);
                var raw = window.atob(base64);
                var rawLength = raw.length;
                var array = new Uint8Array(new ArrayBuffer(rawLength));
    
                for (i = 0; i < rawLength; i++) {
                    array[i] = raw.charCodeAt(i);
                }
                return array;
            }
    View Code

    三、SOAP 方式

            function ShowMailDialog() {
                var file = document.getElementById('upFile').files[0];
                if (file) {
                    UploadFile(file);
                }
            }
            function UploadFile(readFile) {
                var reader = new FileReader();
                reader.readAsArrayBuffer(readFile); //array buffer
                reader.onprogress = updateProgress;
                reader.onload = loaded;
                reader.onerror = errorHandler;
            }
            function loaded(evt) {
                var fileString = evt.target.result;
                var X = _arrayBufferToBase64(fileString); // this is the mothod to convert Buffer array to Binary
                var fileInput = document.getElementById('upFile');
                var fileDisplayArea = document.getElementById('fileDisplayArea');
                var file = fileInput.values;
                var filePath = $('#upFile').val(); // "c:\test.pdf";
                var file = filePath.match(/\([^\]+)$/)[1];
    
                var soapEnv =
                    "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> 
                     <soap:Body>
                         <CopyIntoItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
                             <SourceUrl>" + filePath + "</SourceUrl>
                                 <DestinationUrls>
                                     <string>https://nike.sharepoint.com/teams/ap1/gctech/DEV/Apptexfiles/" + file + "</string>
                                 </DestinationUrls>
                                 <Fields>
                                     <FieldInformation Type='Text' DisplayName='Title' InternalName='Title' Value='Test'  />
                                       <FieldInformation Type='Text' DisplayName='BudgetId' InternalName='BudgetId' Value='8'  />
                                 </Fields>
                             <Stream>" + X + "</Stream>
                         </CopyIntoItems>
                     </soap:Body>
                 </soap:Envelope>";
    
                $.ajax({
                    url: "https://nike.sharepoint.com/teams/ap1/gctech/DEV/_vti_bin/copy.asmx",
                    beforeSend: function (xhr) { xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/CopyIntoItems"); },
                    type: "POST",
                    dataType: "xml",
                    data: soapEnv,
                    complete: processResult,
                    contentType: "text/xml; charset="utf-8""
                });
    
            }
            //SP.SOD.executeOrDelayUntilScriptLoaded(initialize, 'SP.js');
            //SP.SOD.executeOrDelayUntilScriptLoaded(test, 'SP.js');
    
            function errorHandler(evt) {
                if (evt.target.error.name == "NotReadableError") {
                    // The file could not be read.
                }
            }
            function _arrayBufferToBase64(buffer) {
                var binary = ''
                var bytes = new Uint8Array(buffer)
                var len = bytes.byteLength;
                for (var i = 0; i < len; i++) {
                    binary += String.fromCharCode(bytes[i])
                }
                return window.btoa(binary);
            }
            function updateProgress(evt) {
            }
            function processResult(xData, status) {
                alert("Uploaded SuccessFully");
            }
            
    View Code

    四、创建Item及上传附件

    //Create other item with an attachment.
    function CreateOtherItem()
    {
        var otherlist = curWeb.get_lists().getByTitle(otherListTitle);
        var itemCreateInfo = new SP.ListItemCreationInformation();
        var otherItem = otherlist.addItem(itemCreateInfo);
    
        otherItem.set_item("Title", $("#txtReqName").val().trim());
    
        otherItem.update();
        curContext.load(otherItem); //, 'Include(ID, Title)'
        curContext.executeQueryAsync(Function.createDelegate(this, onCreateSucceeded), Function.createDelegate(this, onCreateFailed));
        function onCreateSucceeded(sender, args) {
            var itemId = otherItem.get_item("ID");
            var rootUrl = otherItem.get_item('FileDirRef');
            var attachFolder;
    
            if (!otherItem.get_item('Attachments')) { //Create new folder
                var rootAttachUrl = String.format('{0}/Attachments', rootUrl); //list.get_rootFolder().get_serverRelativeUrl()
                var rootAttachFolder = curWeb.getFolderByServerRelativeUrl(rootAttachUrl);
                attachFolder = rootAttachFolder.get_folders().add("_" + itemId);
                attachFolder.moveTo(rootAttachUrl + '/' + itemId);
                curContext.load(attachFolder);
            }
            else {
                var attachFolderUrl = String.format('{0}/Attachments/{1}', rootUrl, itemId);
                attachFolder = curWeb.getFolderByServerRelativeUrl(attachFolderUrl);
                curContext.load(attachFolder);
            }
            curContext.executeQueryAsync(onSuccess, onFailure);
    
            function onSuccess() {
                var newFile;
                var fileCreateInfo;
                var input = document.getElementById("upApproval");
                var file = input.files[0];
                var freader = new FileReader();
                freader.onload = function (e) {
                    fileCreateInfo = new SP.FileCreationInformation();
                    fileCreateInfo.set_url(file.name);
                    fileCreateInfo.set_overwrite(true);
    
                    var encContent = new SP.Base64EncodedByteArray();
                    var arr = convertDataURIToBinary(e.target.result);
                    for (var i = 0; i < arr.length; ++i) {
                        encContent.append(arr[i]);
                    }
                    fileCreateInfo.set_content(encContent);
    
                    newFile = attachFolder.get_files().add(fileCreateInfo);
                    curContext.load(newFile);
                    curContext.executeQueryAsync();
                    alert("Success!");
                };
                freader.readAsDataURL(file);
            }
            function onFailure() {
                // Error occurred
                alert("Request failed: " + arguments[1].get_message());
                console.log("Request failed: " + arguments[1].get_message());
            }
        }
        function onCreateFailed(sender, args) {
            console.log('Request failed. ' + args.get_message() + '
    ' + args.get_stackTrace());
        }
    }
    View Code
  • 相关阅读:
    Apache ab压力测试时出现大量的错误原因分析
    图解linux下的top命令
    [转载]几种切词工具的使用(转)
    大规模中文文本处理中的自动切词和标注技术
    [转载]盘点:94版《三国演义》演员的今昔对比照
    搜索引擎切词详解
    iphone-命令行编译之--xcodebuild
    Appium IOS 自动化测试初探
    手把手教你appium_mac上环境搭建
    Appium-doctor 检测Xcode未安装问题
  • 原文地址:https://www.cnblogs.com/windy2008/p/5923894.html
Copyright © 2011-2022 走看看