将文件切片作为字节读取并发送到服务器?

时间:2018-01-28 19:57:29

标签: javascript filereader

我想使用FileReader读取一个文件片段,然后将其发送到服务器。这就是我到目前为止所做的:

const createReader = onRead => {
  const reader = new FileReader();
  reader.onloadend = function(evt) {
    if (evt.target.readyState === FileReader.DONE) {
      const arrayBuffer = evt.target.result;
      const bytes = new Uint8Array(arrayBuffer);
      console.log("BYTES: ", bytes);
      onRead(evt.target.result);
    }
  };
  return reader;
};

const reader = createReader(fileSlice => {
  console.log("BYTES: ", fileSlice);
  // send to server
});
reader.readAsArrayBuffer(blob);

这是我上传简单​​的.txt文件时打印的内容:

然而,它返回一个数组,我不知道如何将其转换为我可以通过HTTP发送到我的服务器的格式。

enter image description here

是否有人知道我需要做什么才能将该字节数组转换为最终可以转回原始文件的格式?

2 个答案:

答案 0 :(得分:2)

您可POST Uint8Array到服务器。您可以使用Uint8Array

TextDecoder转换为字符串

答案 1 :(得分:0)

阅读文件块,确保使用readAsArrayBuffer

var readChunck = function (offset, length, file) {
  var r = new FileReader();
  var chunck = file.slice(offset, length + offset);
  r.onload = readEventHandler;
  r.readAsArrayBuffer(chunck)
}

在通气处理程序(readEventHandler)中,将ArrayBuffer转换为Base64String并发布到服务器:

var readEventHandler = function (evt) {

  var data = {
    data: self.arrayBufferToBase64String(evt.target.result)
  }

  self.httpClient.post(url, data)
    .subscribe(data=> {
     // do stuff 
    });

  // ...
}

这是转换功能:

private arrayBufferToBase64String(buffer: ArrayBuffer) {
  let binaryString = ''
  var bytes = new Uint8Array(buffer);
  for (var i = 0; i < bytes.byteLength; i++) {
    binaryString += String.fromCharCode(bytes[i]);
  }

  return window.btoa(binaryString);
}

在服务器端(本例中为ASP Core Web API):

[HttpPost, DisableRequestSizeLimit]
[Route("{blobId}/uploads/{uploadId}/parts/{partNumber}")]
public async Task<IActionResult> UploadPart(
  [FromRoute] string blobId,
  [FromRoute] string uploadId,
  [FromRoute] int partNumber,
  [FromBody] FilePartModel part)
  {
    if (!GuidValidator.IsValidGuid(blobId)) throw new ArgumentException("Invalid BLOB Id");
    if (!GuidValidator.IsValidGuid(uploadId)) throw new ArgumentException("Invalid Upload Id");

    var bytes = Convert.FromBase64String(part.Data);
    using (var stream = new MemoryStream(bytes))
    {
      var etag = await _blobsService.UploadPartAsync(Guid.Parse(blobId), Guid.Parse(uploadId), partNumber, stream);

      return Ok(new FilePart { ETag = etag, PartNumber = partNumber });
    }
}

FilePartModel只是一个简单的模型类:

public class FilePartModel
{
    public string Data { get; set; }
}