1

当我尝试通过上传文件块使用 3 种新方法(StartUpload、ContinueUpload、FinishUpload)上传大文件时,最终上传的文件是损坏的文件,并且大小也大于实际文件。我使用 Rest API 上传大文件。

后续步骤如下:-

  1. 为输入文件创建 HTML。

<input name="FileUpload" type="file" id="uploadInput" className="inputFile" multiple="false" onchange="upload(this.files[0])" />

  1. 下面的方法是代码的起点:

    • 为 siteurl 创建全局变量

var Tasks = {
  urlName: window.location.origin + "/",
  siteName: '/sites/ABC',
};

  1. 调用 Upload() 方法

    • 首先在文件夹中创建大小为 0 的虚拟文件以继续上传大文件。

    • 创建 FileReader 对象,然后开始创建具有 3 个参数(偏移量、长度、方法(即开始/继续/完成上传))的文件块并将块推送到数组中。

    • 为上传创建唯一ID,即uploadID
    • 调用 UploadFile 方法

function upload(file) {
  var docLibraryName = "/sites/ABC/Shared Documents";
  var fileName = $("#uploadInput").val().replace(/C:\\fakepath\\/i, '');
  var folderName = "";
  createDummaryFile(docLibraryName, fileName, folderName)
  var fr = new FileReader();
  var offset = 0;
  var total = file.size;
  var length = 1000000 > total ? total : 1000000;
  var chunks = [];
  fr.onload = evt => {
    while (offset < total) {
      if (offset + length > total)
        length = total - offset;
      chunks.push({
        offset,
        length,
        method: getUploadMethod(offset, length, total)
      });
      offset += length;
    }
    for (var i = 0; i < chunks.length; i++)
      console.log(chunks[i]);
    if (chunks.length > 0) {
      const id = getGuid();
      uploadFile(evt.target.result, id, docLibraryName, fileName, chunks, 0);
    }
  };
  fr.readAsArrayBuffer(file);
}

function createDummaryFile(libraryName, fileName, folderName) {
  return new Promise((resolve, reject) => {
    var endpoint = Tasks.urlName + Tasks.siteName + "/_api/web/GetFolderByServerRelativeUrl('" + libraryName + "/" + folderName + "')/Files/add(url=@TargetFileName,overwrite='true')?" +
      "&@TargetFileName='" + fileName + "'";
    var url;
    const headers = {
      "accept": "application/json;odata=verbose"
    };
    performUpload(endpoint, headers, libraryName, fileName, folderName, convertDataBinaryString(0));
  });
}

function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}

function getGuid() {
  return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0, 3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
}
//check position for selecting method

function getUploadMethod(offset, length, total) {
  if (offset + length + 1 > total) {
    return 'finishupload';
  } else if (offset === 0) {
    return 'startupload';
  } else if (offset < total) {
    return 'continueupload';
  }
  return null;
}

  1. 上传文件方法

    • 将 arraybuffer 转换为 blob 块以开始上传文件

    • 使用我们之前创建的方法和 1mb 偏移量开始实际文件块上传(uploadFileChunk 方法)

    • 启动块循环并调用相同的方法

function uploadFile(result, id, libraryPath, fileName, chunks, index) {
  const data = convertFileToBlobChunks(result, chunks[index]);
  var response = uploadFileChunk(id, libraryPath, fileName, chunks[index], data);
  index += 1;
  if (index < chunks.length)
    uploadFile(result, id, libraryPath, fileName, chunks, index, chunks[index].offset);
}

function convertFileToBlobChunks(result, chunkInfo) {
  var arrayBuffer = chunkInfo.method === 'finishupload' ? result.slice(chunkInfo.offset) : result.slice(chunkInfo.offset, chunkInfo.offset + chunkInfo.length);
  return convertDataBinaryString(arrayBuffer);
}

function convertDataBinaryString(data) {
  var fileData = '';
  var byteArray = new Uint8Array(data);
  for (var i = 0; i < byteArray.byteLength; i++) {
    fileData += String.fromCharCode(byteArray[i]);
  }
  return fileData;
}

  1. UploadFileChunk 方法实际开始上传文件块)

    • 表单字符串如果 startupload 则没有 fileoffset,如果 continueupload 和 finishupload 则它将具有 fileoffset。
    • 调用 performupload 方法开始使用 rest api 上传

function uploadFileChunk(id, libraryPath, fileName, chunk, data) {
  new Promise((resolve, reject) => {
    var offset = chunk.offset === 0 ? '' : ',fileOffset=' + chunk.offset;
    var folderName = "";
    var endpoint = Tasks.urlName + Tasks.siteName + "/_api/web/getfilebyserverrelativeurl('" + libraryPath + "/" + fileName + "')/" + chunk.method + "(uploadId=guid'" + id + "'" + offset + ")";
    const headers = {
      "Accept": "application/json; odata=verbose",
      "Content-Type": "application/octet-stream"
    };
    performUpload(endpoint, headers, libraryPath, fileName, folderName, data);
  });
}

function performUpload(endpoint, headers, libraryName, fileName, folderName, fileData) {
  new Promise((resolve, reject) => {
    var digest = $("#__REQUESTDIGEST").val();
    $.ajax({
      url: endpoint,
      async: false,
      method: "POST",
      headers: headers,
      data: fileData,
      binaryStringRequestBody: true,
      success: function(data) {},
      error: err => reject(err.responseText)
    });
  });
}

请建议为什么上传的文件已损坏并且大小小于或大于实际文件?

提前致谢。

4

1 回答 1

2

我对这段代码有同样的问题。我改为convertFileToBlobChunks只返回ArrayBuffer.

function convertFileToBlobChunks(result, chunkInfo) {
  var arrayBuffer = chunkInfo.method === 'finishupload' ? 
  result.slice(chunkInfo.offset) : result.slice(chunkInfo.offset, chunkInfo.offset + chunkInfo.length);

  return arrayBuffer;
}

我也"Content-Type": "application/octet-stream"从标题中删除了。

完成后,它上传正常。

于 2018-02-22T16:13:44.560 回答