Angular uploaded by reading the file FileReader

First of all this talk about here is only suitable for small to upload files, and there are drawbacks, for large files refer to my other blog post ng2-file-upload + node.js + express file uploads and save local
first reception is through file type select the input file

<input type="file" (change)="selectFile($event)" id="inputBox">

Then read the file and upload

  /**
   * 通过FileReader上传
   * @param event 事件对象
   */
  selectFile(event: any) {
    let reader = new FileReader();
    const appThis = this;
    let fileLength: number = event.target.files[0].size;
    let readLength: number = 5120;
    let tempLength: number = 0;

    if (readLength > fileLength) {
      readLength = fileLength;
    }
    else {
      readLength = 5120;
    }
    reader.readAsDataURL(event.target.files[0]);
    reader.onload = function () {

      appThis.httpService.uploadFile(this.result.slice(20, 5120)).subscribe(data => {
        tempLength = readLength;
        if ((fileLength - readLength) > 0) {
          // 如果文件长度小于以5120增长的读取长度,则读取长度等于文件长度,否则读取长度继续增加5120
          if ((fileLength - (readLength + 5120)) < 0) {
            readLength = fileLength;
          }
          else {
            readLength = readLength + 5120;
          }
          reader.readAsDataURL(event.target.files[0].slice(tempLength, readLength));
        }
        console.log(readLength);
      });
    }
    console.log(event.target.files[0].slice(0, 5120));
  }

Http upload method to prepare the service, not explained

  uploadFile(fileData: string | ArrayBuffer): Observable<any> {
    return this.httpService.post<string>("api/", fileData).pipe(
      map((object): string => object, catchError((object): string => object = '0'))
    );
  }

There, I've done the reading and upload files.Talk about the disadvantages:
First, only a small file upload, upload large files is very slow, then, of course, the code can be called up once the upload size, but I did not try too much, the above example is a 4k, you know, this speed users will hit you of;

Second, upload time can not control, when you finished selecting files to upload carried out, if end-users do not upload it, how much you will produce junk files, if you read the cached data to get out, if you consider the case file is too large it;

The third is the background for the question received, there was a problem cutting files to upload, will stick package, but make sure to get the order back, I did not do this deal, if you are working, you can put the cut data into an object, and simultaneously to compiled object sequence number, the background for splicing in accordance with the writing sequence number, so it requires a fast hardware background big brother.

To sum up three points, the file upload is not recommended to do that

Published 28 original articles · won praise 1 · views 8726

Guess you like

Origin blog.csdn.net/moqiuqin/article/details/98942351