如何使用角4
问题描述:
var fd = new FormData();
fd.append('file', data.target.files[0]);
return this.http.post(url), fd).map().catch();
使用它的工作AngularJS但对角4当我用它不working.I我得到磁盘错误以同样的方式来发送上传excel文件到C#邮政API上载的Excel file.Please帮我。如何使用角4
答
在服务
public importMassUpdateExcel(file: FormData, id): Observable<any> { const headers = new Headers({ 'Authorization': '',//authorization token 'Content-Type': 'application/json; charset=UTF-8'// }); const options = new RequestOptions({ headers: headers }); return this.http .post(url, file, options) .map() .catch(); }
答
下面是一个示例,我用它通过FormData将文件上传到API。
在您的服务文件如upload.service.ts
中,您需要创建函数以通过POST方法上传文件。以下是此功能的例子:
getUploadHeaders() {
let headers = new Headers({'Accept': 'application/json'});
headers.delete('Content-Type');
return headers;
}
addNewPost(newPost: FormData): Observable<FormData> {
const endpoint = 'https://yourApiUrl.com';
return this.http
.post(endpoint, newPost, { headers: this.getUploadHeaders() })
.catch((e) => this.handleError(e));
}
现在你应该在你的组件创建上传功能,例如upload.component.ts
。这里是一个使用FormData上传函数的例子。
fileToUpload: File = null;
constructor(private uploadService: UploadService) { }
handleFileInput(files: FileList) {
this.fileToUpload = files.item(0);
}
saveFileToApi() {
const saveForm: FormData = new FormData();
if (this.fileToUpload) {
saveForm.append('fileFieldNameOnYourApi', this.fileToUpload, this.fileToUpload.name);
}
this.uploadService.addNewPost(saveForm).subscribe(() => {
console.log('Upload success!');
}, error => {
console.log('Upload failed!');
});
}
对于通过上传一个FORMDATA文件需要3个参数:对API端点,文件名该文件因propertyName。 而在你upload.component.html
你需要有形式,像这样的:
<form (ngSubmit)="onSubmit()">
<label for="fileField">Chose file to upload</label>
<input type="file"
id="fileField"
name="fileField"
(change)="handleFileInput($event.target.files)">
<button type="submit">Speichern</button>
</form>
对于FORMDATA的更详细阅读this以及有关FormData.append更多的信息()读取。
谢谢格雷戈尔Doroschenko。你的答案有助于理解,但如果尝试这种方法,我得到'Access-Control-Allow-Origin'标题出现在请求的资源上。这个错误和磁盘错误,所以我通过重新创建授权和内容类型来实现。 –