簡體   English   中英

任何解決方法來實現 angular js 以 angular 上傳多部分/表單數據的功能? 如何在角度中設置未定義的內容類型?

[英]Any work around to achieve the functionality of angular js uploading multipart/form data in angular ? How to set content type undefined in angular?

這只是angular js中用於上傳文件的一段工作代碼。 瀏覽器檢測到的內容類型:'multipart/form-data; 邊界=----WebKitFormBoundaryXPoOG8abcZmXOpiB' 。

$http({
                method: "POST",
                url: url,
                transformRequest: angular.identity,
                headers: {
                    "Authorization": "Bearer " + getToken(),
                    "Content-Type": undefined,
                    "Impersonation": isImpersonation()
                },
                data: formData
            })

現在,我想在 angular 11 中實現相同的結果,但無法設置 content-type:undefined。 也找不到transformRequest的任何選項:angular.identity,

這是我用 angular 寫下的一段代碼,但無法上傳圖像。

 return this.httpClient.post<TRsp>(url, formData, {
      headers: {
        "Authorization": "Bearer " + getToken(),
        "Content-Type": 'multipart/form-data',
      }
    }

誰能告訴我如何將上面的 angular js 代碼轉換為 angular?

設置 Content-type 有時會使您的 api 請求無效。 所以你需要做的是在請求調用中包含空頭。

HTML:

<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">

TS:

fileChange(event) {
    let fileList: FileList = event.target.files;
    if(fileList.length > 0) {
        let file: File = fileList[0];
        let formData:FormData = new FormData();
        formData.append('uploadFile', file, file.name);

        // Do not add content type in headers.
        let headers = new Headers({
          "Authorization": "Bearer " + getToken(),
        });            
        let options = new RequestOptions({ headers: headers });

        this.http.post(`${this.apiEndPoint}`, formData, options)
            .tap(data => console.log("do whatever you want with response data")
            .subscribe();
    }
}

暫無
暫無

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

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