【问题标题】:Ionic XMLHttpRequest FormData empty after append file附加文件后 Ionic XMLHttpRequest FormData 为空
【发布时间】: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


【解决方案1】:

这是一段工作代码(base64 文件上传)。尝试设置标题。将enctype 添加到Access-Control-Expose-Headers 以防止CORS。

 insertPost(data): Observable<any> {
    let headers = new Headers({ "enctype": "multipart/form-data" });
    data.userId = this.globalProvider.userId;
    var form_data = new FormData();
    for (var key in data) {
      form_data.append(key, data[key]);
    }
    return this.http.post(`${baseURL}insertPost`, form_data, { headers: headers })
      .map((response: Response) => {
        return response.json();
      })
      .catch(this.handleError);
  }

【讨论】:

  • 不幸的是,这对我不起作用,我的表单数据在附加文件后仍然为空
  • 为什么不用base64?使用相机插件拍照或从图库中选择它。通过这样做,您可以优化(MB 到 KB)、调整大小、裁剪图像,这将使您的应用程序更快。
  • 我不能使用base64,因为我不能编辑服务器代码,而且服务器只接受输入的文件,所以我需要用这种方式发送
猜你喜欢
  • 2015-11-12
  • 1970-01-01
  • 2017-02-09
  • 2020-10-02
  • 1970-01-01
  • 1970-01-01
  • 2011-06-27
相关资源
最近更新 更多