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
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'標題出現在請求的資源上。這個錯誤和磁盤錯誤,所以我通過重新創建授權和內容類型來實現。 –