您好我想将一个表单发送到我的端点Profile,我的问题出在现场用户:{},因为我无法找到将我的数组放入此字段的方法。
这是我的终端中的字段:
{
"id": 4,
"ci": "123456",
"photo": "http://127.0.0.1:8000/media/profiles/12809632_10208569440535095_617453747387788113_n_zAUAVMf.jpg",
"phone_number": "+59177621589",
"user": {
"id": 5,
"username": "sdanderson",
"first_name": "ssss",
"last_name": "ssss"
},
"experience": "null",
"typeskill": [
{
"id": 1,
"skill_name": "developer"
}
]
}
这是我提出PUT请求的服务:
putProfile(id:string,token:string,body:any,files:any):Observable<Profile>{
//save data to send to the endpoint for update
let formData: FormData = new FormData();
for (let file of files) {
formData.append('photo', file);
}
formData.append('ci',body['ci']);
formData.append('phone_number', body['phone_number']);
formData.append('experience',body['experience']);
formData.append('user',body['user']);//here i have inside the fields: body['user'].id,body['user'].first_name,body['user'].last_name
//include header
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append("Authorization","Token "+ token);
return this.http.put(this.api+"profile/"+id+'/',formData,{headers})
.map(this.extractData)
.catch(this.handleError);
}
答案 0 :(得分:2)
FormData的 append()方法只能接受字符串或 blob 类型的对象。如果需要附加数组,请使用 JSON.stringify()方法将数组转换为有效的JSON字符串。
以下是:
formData.append('user', JSON.stringify(body['user']));
Here您可以阅读有关JavaScript的JSON对象的更多信息。
答案 1 :(得分:2)
尝试这样。.它在我的项目中有效
var formData= new FormData();
for (let file of files) {
formData.append('photo[]', file);
}
答案 2 :(得分:1)
我必须将四个图像添加到相同的formdata id。下面是我的代码
const files = event.target.files;
for(var i=0;i< files.length;i++){
this.formData.append("imgs",files[i]);
}
答案 3 :(得分:0)
尝试使用普通的打字稿对象,而不是使用FormData:
putProfile(id:string,token:string,body:any,files:any):Observable<Profile>{
//save data to send to the endpoint for update
let formData = {
"id": 4,
"ci": body['ci'],
"photo": file,
"phone_number": body['phone_number'],
"user": {
"id": body['user'].id,
"username": "body['user'].username,
"first_name": body['user'].first_name,
"last_name": body['user'].last_name
},
"experience": body['experience'],
"typeskill": [
{
"id": 1,
"skill_name": "developer"
}
]
}
//include header
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append("Authorization","Token "+ token);
return this.http.put(this.api+"profile/"+id+'/',formData,{headers})
.map(this.extractData)
.catch(this.handleError);
}
答案 4 :(得分:0)
我有类似的问题,并且在键中声明了数组。对于您的示例,它看起来像这样:
formData.append('user[id]', body['user']['id']);
...
如果您不想或无法在服务器站点上解析json,这可能会很有用