V
V
Vadim Kravchik2019-01-27 13:06:47
Angular
Vadim Kravchik, 2019-01-27 13:06:47

How can I upload a file along with other data?

I have a form where the photo code below is selected:

<button mat-button type="button" (click)="imgFileInput.click()">Add a photo</button>
      <input hidden formControlName="img" #imgFileInput type="file" name="img" (change)="onFileChanged($event)" [value]="selectedFile"/>

and there is a form handler:
postForm: FormGroup;

constructor(private fb: FormBuilder) {
this.postForm = fb.group({
      'title': [null, Validators.required],
      'content': [null, Validators.compose([Validators.required, Validators.minLength(30)])],
      'category': [null, Validators.required],
      'img': ''
    });
}

onFormSubmit() {
    this._post.savePost(this.postForm);
  }

And on the server function:
router.post('/', upload.single('img'), async (req, res) => {
    console.log(req.file);
    console.log(req.body);
}

So, req.body displays okay, but req.file displays undefiend, why can this be so? maybe I'm not uploading the file correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir, 2019-01-27
@Casufi

Here it is loaded via FileReader
https://medium.com/@amcdnl/file-uploads-with-angul...

R
Roman Mirilaczvili, 2019-01-27
@2ord

In HTML, in the form tag, you need to set the attribute enctype = "multipart/form-data"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question