简体   繁体   中英

How to make a post request with a image file using form-data in ionic-3

My backend is a simple Laravel API , and my API is working properly when I use PostMan application.

I use form data to post my request without any header. it is 100% worked but when I am trying on my ionic code its not working 这是邮递员的要求

-- this is the error --

这是错误的按摩

---this is my backend code error showing in line no 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();
    }
  );}

I want to post my data though post request thank you!

Change the appending order of parameters and append image file as the last parameter to FormData like below.

  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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM