我正在使用以下代码将excel文件从angular 7上传到web API:
<input type="file" (change)="fileEvent($event);">
public fileEvent($event) {
const fileSelected: File = $event.target.files[0];
this.masterService.UploadExcel(fileSelected)
.subscribe((response) => {
console.log('set any success actions...');
return response;
},
(error) => {
console.log('set any error actions...');
});
}
fileToUpload: File = null;
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
服务代码:
UploadExcel(url: string, data: any): Observable<any> {
this.spinner.show();
// headers.append('Content-Type', 'multipart/form-data');
let headers = new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + sessionStorage.getItem('auth_token'),
'CompanyId': sessionStorage.getItem('companyId')
});
debugger;
return this.http.post<any>(AppSettings.apiEndPoint + 'ExcelExample/UploadExcel', data, { headers: headers }).pipe(
map((res: any) => {
this.spinner.hide();
return res
}),
catchError((errorRespnse: any) => {
this.spinner.hide();
var tempMessage = undefined;
tempMessage = errorRespnse.error.ModelState.error[0];
if (tempMessage != undefined) {
this.notificationService.smallBox('error', tempMessage);
}
else {
this.notificationService.smallBox('error', 'Something went wrong, please contact your administrator.');
}
return Observable.throw(errorRespnse);
}));
}
并尝试使用以下服务代码:
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = AppSettings.apiEndPoint + 'ExcelExample/UploadExcel';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
let headers = new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + sessionStorage.getItem('auth_token'),
'CompanyId': sessionStorage.getItem('companyId')
});
return this.http
.post(endpoint, formData, { headers: headers })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
API控制器代码:
[Route("UploadExcel")]
[HttpPost]
public string ExcelUpload()
{
string message = "";
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
// getting 0 count
if (httpRequest.Files.Count > 0)
{
}
}
从API方面,我得到了0个文件计数。
我也尝试以下URLS:
角度文件上传
angular 4字体中的文件上传和下载
首先,尝试将此行添加到App_Start/WebApiConfig.cs
config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));
使用表单数据发布文件
postFile(fileToUpload: File): Observable<boolean> {
const endpoint = AppSettings.apiEndPoint + 'ExcelExample/UploadExcel';
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
let headers = new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + sessionStorage.getItem('auth_token'),
'CompanyId': sessionStorage.getItem('companyId')
});
return this.http
.post(endpoint, formData, { headers: headers })
.map(() => { return true; })
.catch((e) => this.handleError(e));
}
如果它响应任何异常,请张贴到这里