当前位置: 首页>>建站开发>>正文


无法通过REST API将non-text文件上传到SharePoint应用程序

webfans 建站开发 , , , , , 去评论

问题描述

我正在使用以下REST代码将文件添加为SharePoint 2013列表项的附件。

<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

<SharePoint:ScriptLink language="javascript" name="~site/Scripts/js/jquery-1.8.2.js" OnDemand="false" runat="server" Localizable="false"/>

<input id="ufile" type="file" ></input>

<script type="text/javascript">
$(document).ready( 
    doFunc() 
);

function doFunc() {
    var control = document.getElementById("ufile");
    control.addEventListener("change", doAttach, false);
}

var fileName;

function doAttach(event) {
    var files = event.srcElement.files;

    if (!window.FileReader) {
        alert("The FileSystem APIs are not fully supported in this browser.");
        return false;
    }           

    if (files.length > 0) {
        var file = files[0];
        fileName = file.name;

        var reader = new FileReader();
        reader.onload = onLoad;

        reader.onerror = function(event) {
            console.error("File reading error " + event.target.error.code);
        };

        reader.readAsDataURL(file);

    }//     
    return false;
}

function onLoad(event) {
    var contents = event.target.result;

    $.ajax({
        url: "/Test1/_api/web/lists/GetByTitle('List1')/items(1)/AttachmentFiles/add(FileName='" + fileName + "')",
        type: "POST",
        contentType: "application/octet-stream;odata=verbose",
        data: contents, 
        headers: {
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                 },

        success: function (data)
        {
            alert("success");
        },

        error: function (data)
        {
            alert('error' + data.status + ':' + data.statusText + '\n' + data.responseText);
        }
    });
}
</script>       
</asp:Content>

该文件已上传,但包含”incorrect”数据。

例如,一个jpeg文件开始如下:data:image /jpeg; base64,/9j /4AAQSkZJRgABAQEAYABgAAD /…

有人知道SharePoint 2013 REST API是否允许正确上传non-text文件?

最佳解决思路

我能够使用SP.RequestExecutor添加文件

<%-- _lcid="1033" _version="15.0.4128" _dal="1" --%>
<%-- _LocalBinding --%>
<%@ Page language="C#" MasterPageFile="~masterurl/default.master"    Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,Microsoft.SharePoint,Version=15.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c" meta:progid="SharePoint.WebPartPage.Document" meta:webpartpageexpansion="full"  %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Import Namespace="Microsoft.SharePoint" %> <%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">

<SharePoint:ScriptLink language="javascript" name="~site/Scripts/js/jquery-1.8.2.js" OnDemand="false" runat="server" Localizable="false"/>

<input id="ufile" type="file" ></input>

<script type="text/javascript">
$(document).ready( dofunc() );

function dofunc() {
    var control = document.getElementById("ufile");
    control.addEventListener("change", fdocattach, false);
}

var file;
var contents;

function fdocattach(event) {
    var i = 0,
    files = event.srcElement.files,
    len = files.length;

    for (; i < len; i++) {
        console.log("Filename: " + files[i].name);
        console.log("Type: " + files[i].type);
        console.log("Size: " + files[i].size + " bytes");
    }

    if (!window.FileReader) {
        alert("The FileSystem APIs are not fully supported in this browser.");
        return false;
    }           

    if (files.length > 0) {
        file = files[0];
        fileName = file.name;

        var reader = new FileReader();
        reader.onload = fonload;

        reader.onerror = function(event) {
            console.error("File reading error " + event.target.error.code);
        };
        reader.readAsArrayBuffer(file);
    }       
    return false;
}

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 binary;

}

function fonload(event) {
    contents = event.target.result;
            $.getScript("https://addinexpress966.sharepoint.com/Test1/_layouts/15/SP.RequestExecutor.js", fonload2);
}

function fonload2() {
    var contents2 = _arrayBufferToBase64(contents);

    var createitem = new SP.RequestExecutor("https://addinexpress966.sharepoint.com/Test1");
    createitem.executeAsync({
        url: "https://addinexpress966.sharepoint.com/Test1/_api/web/lists/GetByTitle('List1')/items(1)/AttachmentFiles/add(FileName='" + file.name + "')",
        method: "POST",
        binaryStringRequestBody: true,
        body: contents2,
        success:  fsucc,
        error: ferr,
        state: "Update"
    });

    function fsucc(data)
    {
        alert('success');
    }       
    function ferr(data)
    {
        alert('error\n\n' + data.statusText + "\n\n" + data.responseText);
    }       
}

</script>       

</asp:Content>

次佳解决思路

在阅读和大量的小提琴之后,我想出了将data属性设置为file和processData为false的方法。这很好,除了dropfile不支持readAsArrayBuffer。

所以我使用了上面的convertDataURIToBinary函数。现在我有这个,它很好。备注:在加载事件中添加files.data,我必须在将多个文件附加到listitem时变成异步。

jQuery.ajax({
    url: listUrl + "/items(" + id + ")/AttachmentFiles/add(FileName='" + file.name + "')",
    type: "POST",
    async: false,
    processData: false,
    headers: {
        "accept": "application/json;odata=verbose",
        "X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
    },
    data: convertDataURIToBinary(file.data),
    success: function(e) { _.log(_.logType.verbose, "File uploaded: " + e); },
    error: function(e) { _.log(_.logType.warning, "File not uploaded: " + e); }
});

var convertDataURIToBinary = function(dataURI) {
    var base64Marker = ";base64,";
    var base64Index = dataURI.indexOf(base64Marker) + base64Marker.length;
    var base64 = dataURI.substring(base64Index);
    var raw = window.atob(base64);
    var rawLength = raw.length;
    var array = new window.Uint8Array(new window.ArrayBuffer(rawLength));

    for (i = 0; i < rawLength; i++) {
        array[i] = raw.charCodeAt(i);
    }
    return array;
};

var filesDropped = function (e) {
    e = e || window.event;
    var files = (e.files || e.dataTransfer.files);

    jQuery(files).each(function (index, element) {
        var fileReader = new FileReader();
        fileReader.file = element;
        fileReader.onload = fileLoaded;
        fileReader.onerror = function () {
            _.log(_.logType.warning, "Error reading file: " + this.file.name);
        };
        fileReader.readAsDataURL(element);
    });

    return false;
};

var fileLoaded = function (fileOnloadEvent) {
    this.file.data = fileOnloadEvent.target.result;
    var filename = this.file.name.toLowerCase();
    jQuery(vm.files()).each(function (fIndex, fElement) {
        if (fElement.name.toLowerCase() === filename)
            vm.removeFile(fElement);
    });
    vm.files.push(this.file);
};

参考资料

本文由朵颐IT整理自网络, 文章地址: https://duoyit.com/article/2006.html,转载请务必附带本地址声明。