简体   繁体   中英

Cannot set Content-Type in Angular FileUpload control

I have an PrimeNG FileUpload control in my Angular project and I manually invoke upload method as shown on PrimeNG manually invoke FileUpload . However, although I have properly fill the files parameter with file data, the data lost its value and returns null after passing from service.ts to Controller (ASP.NET MVC). I think the problem is caused by not being able to set Content-Type in none of the events as shown below:

onBeforeSendFile(event: any) {
    event.xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    event.xhr.setRequestHeader("Content-Type", "multipart/form-data");
}

or

onBeforeUploadFile(event: any) {
    event.xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    event.xhr.setRequestHeader("Content-Type", "multipart/form-data");
}

etc...

I encounter "Cannot read property 'setRequestHeader' of undefined" error ath the setRequestHeader lines. Could you please inform me how can I set the necessary RequestHeaders and not lost the file data?

Update: Here is my post method below:

 post(url: string, body: any, comp?: BaseComponent): Observable<any> {
    this.requestInterceptor(comp);
    return this.http.post<any>(url, { body: JSON.stringify(body) },
        {
            headers: new HttpHeaders({  // set the header values here
                'Content-Type': 'multipart/form-data',
                'X-Requested-With': 'XMLHttpRequest',
                'Test-Header': 'This is just a test header!'
            })
        }
    ).pipe(
        catchError((error, obs) => this.handleError(error, comp)),
        tap((res: Response) => {
            this.onSubscribeSuccess(res, comp);
        }, (error: any) => {
            this.onSubscribeError(error, comp);
        }),
        finalize(() => {
            this.onFinally(comp);
        }));
}

You can use HttpClient instead like:

this._HttpClient.post('url whatever', { 'body': 'here' }, {
    headers: new HttpHeaders({  // set the header values here
        'Content-Type': 'multipart/form-data'
    })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM