如何将文件上传到Angular 4应用程序中的SharePoint Online库?

时间:2018-04-03 17:30:53

标签: javascript jquery angular typescript sharepoint

我正在使用Angular SPA应用程序。 我正在使用SP.js& SP.Requestor.js有用,可以上传相同但没有一个似乎是Angular 4 App的工作。

import pandas as pd
df = pd.read_csv(your_file_here, header=None, names=['name', 'surnames', 'id', 'country'])  # I am assuming you don't have header
temp = df[df.name == 'name:z'].iloc[0]  # save the first row with name:z
df_new = df[df.name != 'name:z']  # drop all rows with name z
df_new = df_new.append(temp)  # append the first row back
df_new.to_csv(new_file_name)  # if you want to save

executeAsync 中获取以下错误:

  

ErrorPage.PostMessage:Origin = https://localhost:44316,   数据= {"命令":"查询"" postMessageId":" SP.RequestExecutor3"" responseAvailable&#34 ;:假,#&34;的errorCode": - 1007"的errorMessage":"相关   ID:e12d5a9e-b0d6-0000-745f-24b31dd971a6"}   vendor.js?v = T82_qgC1tKr4vAoag-4pr9ch_dUDSit3nEgaqP4H0Ec:12090 ERROR

     

错误:未捕获(承诺):未定义       at resolvePromise(vendor.js?v = T82_qgC1tKr4vAoag-4pr9ch_dUDSit3nEgaqP4H0Ec:87020

1 个答案:

答案 0 :(得分:0)

我们可以使用jQuery上传文件,这是一个供您参考的演示:

HTML:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
<input id="getFile" type="file"/><br />
<input id="displayName" type="text" value="Enter a unique name" /><br />
<input id="addFileButton" type="button" value="Upload" onclick="uploadFile()"/>

JS代码:

'use strict';

jQuery(document).ready(function () {

   // Check for FileReader API (HTML5) support.
   if (!window.FileReader) {
       alert('This browser does not support the FileReader API.');
   }
});

// Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() {

// Define the folder path for this example.
var serverRelativeUrlToFolder = '/shared documents';

// Get test values from the file input and text input page controls.
var fileInput = jQuery('#getFile');
var newName = jQuery('#displayName').val();

// Get the server URL.
var serverUrl = _spPageContextInfo.webAbsoluteUrl;

// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer();
getFile.done(function (arrayBuffer) {

    // Add the file to the SharePoint folder.
    var addFile = addFileToFolder(arrayBuffer);
    addFile.done(function (file, status, xhr) {

        // Get the list item that corresponds to the uploaded file.
        var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
        getItem.done(function (listItem, status, xhr) {

            // Change the display name and title of the list item.
            var changeItem = updateListItem(listItem.d.__metadata);
            changeItem.done(function (data, status, xhr) {
                alert('file uploaded and updated');
            });
            changeItem.fail(onError);
        });
        getItem.fail(onError);
    });
    addFile.fail(onError);
});
getFile.fail(onError);

// Get the local file as an array buffer.
function getFileBuffer() {
    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(fileInput[0].files[0]);
    return deferred.promise();
}

// Add the file to the file collection in the Shared Documents folder.
function addFileToFolder(arrayBuffer) {

    // Get the file name from the file input control on the page.
    var parts = fileInput[0].value.split('\\');
    var fileName = parts[parts.length - 1];

    // Construct the endpoint.
    var fileCollectionEndpoint = String.format(
            "{0}/_api/web/getfolderbyserverrelativeurl('{1}')/files" +
            "/add(overwrite=true, url='{2}')",
            serverUrl, serverRelativeUrlToFolder, fileName);

    // Send the request and return the response.
    // This call returns the SharePoint file.
    return jQuery.ajax({
        url: fileCollectionEndpoint,
        type: "POST",
        data: arrayBuffer,
        processData: false,
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            "content-length": arrayBuffer.byteLength
        }
    });
}

// Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
function getListItem(fileListItemUri) {

    // Send the request and return the response.
    return jQuery.ajax({
        url: fileListItemUri,
        type: "GET",
        headers: { "accept": "application/json;odata=verbose" }
    });
}

// Change the display name and title of the list item.
function updateListItem(itemMetadata) {

    // Define the list item changes. Use the FileLeafRef property to change the display name. 
    // For simplicity, also use the name as the title. 
    // The example gets the list item type from the item's metadata, but you can also get it from the
    // ListItemEntityTypeFullName property of the list.
    var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
        itemMetadata.type, newName, newName);

    // Send the request and return the promise.
    // This call does not return response content from the server.
    return jQuery.ajax({
        url: itemMetadata.uri,
        type: "POST",
        data: body,
        headers: {
            "X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
            "content-type": "application/json;odata=verbose",
            "content-length": body.length,
            "IF-MATCH": itemMetadata.etag,
            "X-HTTP-Method": "MERGE"
        }
    });
 }
}

// Display error messages. 
function onError(error) {
    alert(error.responseText);
}