这是我的问题..。
我正在尝试通过Angular 6上传一个文件到Teamwork API https://developer.teamwork.com/projects/file-uploading/upload-a-file,但是无论我尝试上传什么文件,我总是得到错误消息"the form field ' file‘no not message a valid file“。
我尝试在不使用content-type、content-type: undefined等的情况下发送,我尝试将file对象添加到formdata中
下面是一些代码:
-模板文件
<input type="file" [id]="question.id" class="form-control" (change)="onUpload($event)">
<button class="btn btn-update"><i class="icon-success file-continue" (click)="onUpdate($event)"></i></button>-组件
onUpload(event: any) {
this.uploadObject = event.target.files[0];
this.uploadName = event.target.files[0].name;
}
onUpdate(event: any) {
this.twApiService.uploadFile(this.uploadObject).subscribe(
(response: any) => {
console.log(response);
},
(error: any) => {
console.log(error);
}
);
}-服务--
uploadFile(uploadObject: any) {
const url = 'https://[hidden].teamwork.com/pendingfiles.json';
const fileObject = { file: uploadObject };
const headers = new HttpHeaders({'Content-Type': 'multipart/form-data', 'Authorization': 'BASIC ' + window.btoa(this.key + ':xxx')});
return this.http.post(url, fileObject, {headers});
}在过去的3天里,我尝试了很多版本的代码,在互联网上找到的所有东西都没有起作用。我总是收到这样的错误:“表单域'file‘不包含有效的文件”
谁能给我一些如何解决这个问题的说明,或者至少尝试一些不同的东西?
问候你,伊沃。
发布于 2019-05-31 20:13:26
我检查了teamwork API及其奇怪之处,因为它们需要一个请求体application/json (通常文件上传是通过formdata请求来处理的)
因此请先尝试此操作,并在网络选项卡中检查这是application/json请求:
uploadFile(uploadObject: any) {
const url = 'https://[hidden].teamwork.com/pendingfiles.json';
const fileObject = { file: uploadObject };
const headers = new HttpHeaders({'Authorization': 'BASIC ' + window.btoa(this.key + ':xxx')});
return this.http.post(url, fileObject, {headers});
}如果不起作用,尝试formData方式很重要,不要手动设置formData类型,因为它会自动识别它。
uploadFile(uploadObject: any) {
const url = 'https://[hidden].teamwork.com/pendingfiles.json';
const formData = new FormData();
formData.append('file', uploadobject);
const headers = new HttpHeaders({'Authorization': 'BASIC ' + window.btoa(this.key + ':xxx')});
return this.http.post(url, formData, {headers});
}https://stackoverflow.com/questions/56393893
复制相似问题