Error attaching Angular4 file

Asked

Viewed 136 times

0

I’m trying to get a file attached through a button. The problem is that the file arrives but is not setting, as shown in the images below, just below the images has the method and the html button.

Erro SetValue

Arquivo chega null

docFile(event: any) {
  let reader = new FileReader();
  let size = event.target.files[0].size;
  if (event.target.files && event.target.files.length > 0) {
    let file = event.target.files[0];
    if (size > 2097152) {
      this.template.openModal()
    } else {
      reader.readAsDataURL(file);
      reader.onload = (event: any) => {
        this.imagemDoc = event.target.result;
        console.log(size);
        this.dadosPessoaisForm.get('documentos.arquivo').setValue({
          id: this.arquivo.id,
          nome: file.name,
          tipo: file.type,
          // dados: reader.result.split(',')[1]
        })
      };
    }
  }
}
<div class="input-group-addon" style="background-color: #ffffff">
  <div class="upload-btn-wrapper">
    <button type="file" class="fa fa-paperclip"></button>
    <input type="file" class="btn btn-default" id="arquivo" accept='file/*' (change)="docFile($event)" #fileInput>
  </div>
</div>

The console.log(size) was made in the function as requested in the comment and the result was this of the image below.

inserir a descrição da imagem aqui

  • You can give a console. log to Event.target.files and see if the structure is correct ?

  • I just did and the result is in the last lines of my question.

2 answers

1

You can do this way to perform the upload.

app.component.html

<form [formGroup]="photoForm" class="row" (submit)="upload()">
    <input #fileInput formControlName="file" type="file" accept="image/*"
       (change)="handleFile($event.target.files[0])">
</form>

And Handle serves to pick up the file at the time it is chosen and inside the variable file of the kind File and preview of the kind string globally within the Component.ts.

And to perform the upload will be the method upload will be called in the form Ubmit. In this example I am sending the image along with other fields of the form. I kept separate the file so you can adapt in the best way.

app.componentts.

export class AppComponent implements OnInit {

    photoForm: FormGroup;
    file: File;

    constructor(
        private formBuilder: FormBuilder,
        private appService: AppService,
        private router: Router
    ) { }

    ngOnInit() {

        this.photoForm = this.formBuilder.group({
            file: [''],
            description: ['']
        });
    }

    handleFile(file: File) {
        this.file = file;
        const reader = new FileReader();

        reader.onload = (event: any) => this.preview = event.target.result;
        reader.readAsDataURL(file);
    }


    upload() {
        const data = this.photoForm.getRawValue() as PhotoForm;
        data.file = this.file; // <-- arquivo para upload

        this.appService.upload(data).subscribe(
            () => {
                console.log('Upload Done.')
            }
        );
    }

And finally the service. I am explicitly declaring each field of my form because the backend expects different names than those applied in the frontend.

app.service.ts

    upload(photoForm: PhotoForm) {

        const formData = new FormData();
        formData.append('description', photoForm.description);
        formData.append('imageFile', photoForm.file);

        return this.http.post(API + '/photos/upload', formData);
    }

I hope it helps! Good codes!

  • You can demonstrate in stackblitz because I could not understand the app.componente.ts .

  • I modified a little trying to simplify and clarify your doubts. See if it helps. @Fabianocamargo

0


I had forgotten to mention that this file is inside an array, and it was necessary to pass the array position first and then the field where I place the file attachment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.