【发布时间】:2017-12-06 14:44:57
【问题描述】:
我正在尝试使用 ionic 2 发送带有帖子的文件
为了请求文件,我使用了一个不可见的输入类型文件
<input type="file" accept="image/*;" #file id="fileUpoload" style="display: none">
按钮调用函数是这样的:
(click)="onFileUpoloadButtonPressed(file)"
这是调用的函数:
onFileUpoloadButtonPressed(element){
document.getElementById("fileUpoload").onchange = function(e : any){
let file = {
name: e.srcElement.files[0].name,
file: e.srcElement.files[0],
};
//I get the id of the user since i have to perform an edit call to my api
this.storage.get("userLogged").then((value) => {
setTimeout(function(){
this.postChangeAvatar(this, parseInt(value.data.utenti_id), file,
function (ext, result){ //Success callback
console.log(result);
},
function(ext, error){ //Error callback
console.log(error);
alert(error);
}
)
}, 100)
})
}
element.click();
}
这是执行 post 请求的 postChangeAvatar 函数:
postChangeAvatar(ext, id, file, successCallback, errorCallback){
let formData : any = new FormData();
let xhr : any = new XMLHttpRequest();
console.log(id);
console.log(file); //File is successfully get
formData.append('user_photo', file.file, file.name);
for (var pair of formData.entries()) { //This is showing nothing
console.log(pair[0]+ ', ' + pair[1]);
}
xhr.onreadystatechange = () => {
if (xhr.readyState == 4){
if (xhr.status == 200){
successCallback(ext, xhr.response);
}
else {
errorCallback(ext, xhr.response);
}
}
}
xhr.open('POST', "http://xxxxxxxxxx/api/edit/utenti/" + id, true);
xhr.send(formData);
}
post 已执行,但 formData 在追加文件后仍然为空,尝试使用 for each 打印 formdata 没有显示任何内容,所以唯一的错误是执行 post 时 formData 为空
如您所见,我尝试将整个请求封装在 setTimeout 中,以确保获得文件,文件在其中但未在 formData 中追加
从服务器我可以看到请求的主体是空的 我在另一个项目中尝试了这种方法,并且成功地工作了,所以看到它不起作用我有点惊讶
如果我无法完成这项工作,也许还有另一种方法可以使用 ionic 2 发布选定的文件?
【问题讨论】:
-
这个问题你解决了吗?
-
@keshav 很遗憾没有,我至少必须使用 base64
标签: http post ionic2 xmlhttprequest form-data