1

Hello friends I created a project in angular 4 I want to upload an image and sent request to the PHP file but form-data can't append values and images. please help me I include FormGroup, FormControl, FormBuilder, Validators, Http

const Image = this.com_Image.nativeElement;
if (Image.files && Image.files[0]) {
  this.comImageFile = Image.files[0];
}
const ImageFile: File = this.comImageFile;

// [enter image description here][1]
let formData = new FormData();
formData.append('companyName', value.companyName);
formData.append('username', value.username);
formData.append('uploadFile', ImageFile, ImageFile.name);

console.log(formData);
2
  • Is sending it as a base64 string an option for you? Commented Sep 6, 2018 at 14:06
  • no i cant find result i my formdata Commented Sep 6, 2018 at 14:10

2 Answers 2

1

Html

<input #fileSelect type="file" class="form-control" (change)="onFileChanged($event)" accept=".jpg, .png"/>

component

export class FileUploadComponent {
  @ViewChild('fileSelect') fileSelectInput: ElementRef;

  fileToUpload: any;

  onFileChanged(event) {
    // https://stackoverflow.com/questions/13602039/e-srcelement-is-undefined-in-firefox
    this.fileToUpload = (event.srcElement || event.target).files; 
    let formData: FormData = new FormData();
    formData.append('file', this.fileToUpload[0]);
    this.createOrUpdateResource(formData);   
  }

  // https://stackoverflow.com/questions/48059121/angular4-file-upload-put-request-fails, 
  so making this POST
  private createOrUpdateResource(formData: FormData) {
    this.http.post<any>(`http://localhost:8080/upload`, formData).subscribe((res) => {
      //success
    }, error => {
      //error
    });
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

i have a doubt bro formdata append is not working without image upload also
@James what do you mean by formdata append not working?
can't append values in the formdata
1

Have you tried to pass only name and value for the image?

For file management (in general) this has worked for me:

formData.append('uploadFile', ImageFile);

1 Comment

formdata append is not working without image upload also

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.