使用SPServices.js更新列表项后重定向到列表视图

时间:2018-04-01 14:01:56

标签: javascript sharepoint-2013 spservices

我创建了一个自定义表单来提交列表项并附加多个附件。

在将所有附件附加到列表项后,需要将用户重定向到默认列表视图。 我尝试添加window.location.href ='默认列表网址'但它会在添加附件时重定向。 它适用于小文件,但对于大文件,只添加1个附件。 这是片段: HTML:



var ListTitle = "SubTask";

$( document ).ready(function() {
//$('#attachment').multifile();
    $("#NewSaveItem").click(function() {
    CreateNewItem();
         
});
    
    
});

function CreateNewItem() {
    var data = {
        __metadata: { 'type': "SP.Data.SubTaskListItem" },
        Title: $('#Title').val()
    };

    $.ajax({
        //_spPageContextInfo.webAbsoluteUrl get current SharePoint site url
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('" + ListTitle + "')/Items",
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        // to make sync calls.
        async: false,
        data: JSON.stringify(data),
        success: function (data) {
            if (data.d.ID != undefined && data.d.ID > 0){
                //Uploads files to SharePoint List item
                UploadFileToListItem(data.d);
                
                }
            else
            {
                console.log('Item added successfully');
                }
        },
        error: function (error) {
            console.log('Problem saving data');
        }
    });
   // window.location.href = 'https://connect.sharepoint.com/sites/SpApps/Lists/SubTask/';

}



//Once the item is created now let’s try to upload documents to SharePoint list item.

function UploadFileToListItem(data) {
    var element = document.getElementById("attachment");
    lastFileName = element.files[element.files.length - 1].name;
    for (var i = 0; i < element.files.length; i++) {
        var file = element.files[i];
        uploadFile(data, file);
    }
    alert('Done');
    window.location.href = 'https://connect.sharepoint.com/sites/SpApps/Lists/SubTask/';
}

//uploads single file at a time.
function uploadFile(data, file) {
    var getFileBuffer = function (file) {
        var deferred = $.Deferred();
        var reader = new FileReader();

        reader.onload = function (e) {
            deferred.resolve(e.target.result);
        }

        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }

        reader.readAsArrayBuffer(file);

        return deferred.promise();
    };
    
    getFileBuffer(file).then(function (buffer) {
        var binary = "";
        var bytes = new Uint8Array(buffer);
        var i = bytes.byteLength;
        while (i--) {
            binary = String.fromCharCode(bytes[i]) + binary;
        }
        var fileName = file.name;
        var error = ''
        $().SPServices({
            operation: "AddAttachment",
            async: false,
            listName: ListTitle,
            listItemID: data.Id,
            fileName: fileName,
            attachment: btoa(binary),
            completefunc: function (xData, Status) {
                console.log(file.name + " uploaded");
            }
        });
    });
    
    
}
&#13;
<table align="left" border="1" cellpadding="0" cellspacing="0" >
<tbody>
<tr>
<td  valign="top">
<h3> Name</h3>
</td>  
<td valign="top" style="padding:9px;">  
<input type="text" value="" maxlength="255" id="Title" title="Name" style="width: 96%;" ms-spellcheck-true">  
</td>
</tr>
                                
<tr >
<td >
<span style="font-family: " segoe ui" ,sans-serif; color: #444444">
Click here to attach file
</span> 
<div id="attachFilesHolder ">  
 <input type="file" id="attachment" name="FileUpload" multiple/>
</div>  
</td>
<td>
</td>
</tr>
</table>
<div>
<input name="SaveItem" style=" height: 40px; font-size: 15px;" id="NewSaveItem" accesskey="O" onclick="" type="button" value="Click here to submit " target="_self">
</div>  
&#13;
&#13;
&#13;

请让我知道我哪里出错。

1 个答案:

答案 0 :(得分:0)

在SPServices完成func中定义uploadedCount变量,然后在将文件上传到列表项时,检查上传框中的文件数是否等于上传的计数,然后使用SetInterval进行跟踪:

var ListTitle = "SubTask";
var fileCount=0;
var uploadCount=0;
$( document ).ready(function() {
    //$('#attachment').multifile();
    $("#NewSaveItem").click(function() {
        CreateNewItem();        
    });      
});

function CreateNewItem() {
    var data = {
        __metadata: { 'type': "SP.Data.SubTaskListItem" },
        Title: $('#Title').val()
    };
    $.ajax({
        //_spPageContextInfo.webAbsoluteUrl get current SharePoint site url
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('" + ListTitle + "')/Items",
        type: "POST",
        headers: {
            "accept": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "content-Type": "application/json;odata=verbose"
        },
        // to make sync calls.
        async: false,
        data: JSON.stringify(data),
        success: function (data) {
            if (data.d.ID != undefined && data.d.ID > 0){
                //Uploads files to SharePoint List item
                UploadFileToListItem(data.d);               
            }
            else
            {
                console.log('Item added successfully');
            }
        },
        error: function (error) {
            console.log('Problem saving data');
        }
    });
   // window.location.href = 'https://connect.sharepoint.com/sites/SpApps/Lists/SubTask/';

}

//Once the item is created now let’s try to upload documents to SharePoint list item.
function UploadFileToListItem(data) {
    var element = document.getElementById("attachment");
    lastFileName = element.files[element.files.length - 1].name;

    //file count
    fileCount=element.files.length;
    for (var i = 0; i < element.files.length; i++) {
        var file = element.files[i];
        uploadFile(data, file);
    }
    //alert('Done');
    setInterval(function(){ 
        if(fileCount!=0&&fileCount==uploadCount){
            window.location.href = 'https://connect.sharepoint.com/sites/SpApps/Lists/SubTask/';
        }
    }, 1000);   
}

//uploads single file at a time.
function uploadFile(data, file) {
    var getFileBuffer = function (file) {
        var deferred = $.Deferred();
        var reader = new FileReader();

        reader.onload = function (e) {
            deferred.resolve(e.target.result);
        }

        reader.onerror = function (e) {
            deferred.reject(e.target.error);
        }

        reader.readAsArrayBuffer(file);

        return deferred.promise();
    };

    getFileBuffer(file).then(function (buffer) {
        var binary = "";
        var bytes = new Uint8Array(buffer);
        var i = bytes.byteLength;
        while (i--) {
            binary = String.fromCharCode(bytes[i]) + binary;
        }
        var fileName = file.name;
        var error = ''
        $().SPServices({
            operation: "AddAttachment",
            async: false,
            listName: ListTitle,
            listItemID: data.Id,
            fileName: fileName,
            attachment: btoa(binary),
            completefunc: function (xData, Status) {
                console.log(file.name + " uploaded");
                uploadCount++;
            }
        });
    });     
}