簡體   English   中英

Angular-將文件上傳為base64

[英]Angular - upload file as base64

我正在嘗試將文件從Angular 4應用程序上傳到接受base64字符串作為文件內容的JSON API服務。

所以我要做的是-使用FileReader.readAsDataURL讀取文件,然后當用戶確認上傳時,我將向API創建一個JSON請求並發送我之前獲取的文件的base64字符串。

這是問題開始的地方-一旦我對“內容”(將其記錄,發送,發送)執行某項操作,請求將被發送,但是它的速度非常慢,例如2MB文件需要20秒。

我試過了:

  • 使用ArrayBuffer並將其手動轉換為base64
  • 將base64字符串存儲為HTML並在以后檢索
  • 用戶單擊上載按鈕后讀取文件
  • 使用@angular/common的舊客戶端
  • 使用普通的XHR請求

但一切都會導致相同的結果。

我知道問題出在哪里。 但是為什么會發生呢? 它是特定於瀏覽器還是特定於角度的? 有沒有更喜歡的方法(請記住,它必須是base64字符串)?


筆記:

  • 更改API中的任何內容都是我無法控制的
  • API很好,發送任何文件通過郵遞員將立即完成

碼:

當用戶將文件添加到放置區時,此方法運行:

public onFileChange(files: File[]) : void {
    files.forEach((file: File, index: number) => {
        const reader = new FileReader;

        // UploadedFile is just a simple model that contains filename, size, type and later base64 content
        this.uploadedFiles[index] = new UploadedFile(file);

        //region reader.onprogress
        reader.onprogress = (event: ProgressEvent) => {
            if (event.lengthComputable) {
                this.uploadedFiles[index].updateProgress(
                    Math.round((event.loaded * 100) / event.total)
                );
            }
        };
        //endregion

        //region reader.onloadend
        reader.onloadend = (event: ProgressEvent) => {
            const target: FileReader = <FileReader>event.target;
            const content = target.result.split(',')[1];

            this.uploadedFiles[index].contentLoaded(content);
        };
        //endregion

        reader.readAsDataURL(file);
    });
}

用戶單擊“保存”按鈕時運行此方法

public upload(uploadedFiles: UploadedFile[]) : Observable<null> {
    const body: object = {
        files: uploadedFiles.map((uploadedFile) => {
            return {
                filename: uploadedFile.name,
                // SLOWDOWN HAPPENS HERE
                content: uploadedFile.content
            };
        })
    };

    return this.http.post('file', body)
}

為了將大文件發送到服務器,您應該使用FormData使其能夠作為多部分發送,而不是單個大文件。

就像是:

 // import {Http, RequestOptions} from '@angular/http'; uploadFileToUrl(files, uploadUrl): Promise<any> { // Note that setting a content-type header // for mutlipart forms breaks some built in // request parsers like multer in express. const options = new RequestOptions(); const formData = new FormData(); // Append files to the virtual form. for (const file of files) { formData.append(file.name, file) } // Send it. return this.http.post(uploadUrl, formData, options); } 

另外,不要忘記設置標題'Content-Type': undefined ,我已經花了好幾個小時摸索了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM