【问题标题】:How to make a post request with a image file using form-data in ionic-3如何使用 ionic-3 中的表单数据使用图像文件发出发布请求
【发布时间】:2019-01-18 16:39:03
【问题描述】:

我的后端是一个简单的 Laravel API,当我使用 PostMan 应用程序时,我的 API 可以正常工作。

我使用表单数据发布我的请求而没有任何标题。它是 100% 工作的,但是当我尝试我的离子代码时它不起作用

-- 这是错误--

---这是我在第 55 行显示的后端代码错误:

selectphoto(){

const options: CameraOptions = {
  quality: 50,
  destinationType: this.camera.DestinationType.FILE_URI,
  sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
  saveToPhotoAlbum: false }

this.camera.getPicture(options).then((imageData) => {
  // imageData is either a base64 encoded string or a file URI
  // If it's base64 (DATA_URL): base64Image = 'data:image/jpeg;base64,' + imageData;
  this.image = normalizeURL(imageData);
 }, (err) => {
  // Handle error
 });}

 onSubmit(form:NgForm){

  console.log('img' , this.image);
  this.actorBestMovie = form.value.actorBestMovie;
  this.actorCountry = form.value.actorCountry;
  this.actorFirstMovie = form.value.actorFirstMovie;
  this.actorImdbBestMovie = form.value.actorImdbBestMovie;
  this.actorName = form.value.actorName;
  this.actorpost();
  form.reset()  
}

 actorpost() {

  let headers = new Headers();
  headers.append("Accept", "application/json");
  let body = new FormData();
  body.append('file',this.image);
  body.append('name',this.actorName); 
  body.append('country',this.actorCountry );
  body.append('first_movie',this.actorFirstMovie);
  body.append('best_movie',this.actorBestMovie);
  body.append('imdb_best_movie',this.actorImdbBestMovie); 

this.http.post("http://localhost/slreview-api/public/api/actors",body,{headers: headers })
  .map(res => res.json())
  .subscribe(
    data => {
      console.log("data => ", data);
    },
    error => {
      console.log('Error => ', error);
    },
    () => {
      console.log('Completed!');
      this.presentToast();
    }
  );}

我想通过发布请求发布我的数据 谢谢!

【问题讨论】:

    标签: angular typescript ionic-framework ionic3 httpclient


    【解决方案1】:

    更改参数的附加顺序,并将图像文件作为最后一个参数附加到FormData,如下所示。

      let body = new FormData();
      body.append('name',this.actorName); 
      body.append('country',this.actorCountry );
      body.append('first_movie',this.actorFirstMovie);
      body.append('best_movie',this.actorBestMovie);
      body.append('imdb_best_movie',this.actorImdbBestMovie);
      body.append('file',this.image);
    

    【讨论】:

    • 它仍然无法正常工作.. 图像文件请求中的错误这是错误 -----> {message: "Call to a member function store() on null",...} 异常:" Symfony\Component\Debug\Exception\FatalThrowableError”文件:“C:\xampp\htdocs\slreview-api\app\Http\Controllers\ActorController.php”行:55 消息:“调用成员函数 store() on null " ----> 错误行是我在后端请求的图像文件
    猜你喜欢
    • 2019-07-20
    • 2019-03-07
    • 2017-04-12
    • 2018-07-03
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多