PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How to upload file from frontend to backend

 October 14, 2022     axios, express-fileupload, react-query, reactjs, typescript     No comments   

Issue

I am developing a full stack web-app as part of my thesis. One of the things I am supposed to implement is the ability to send csv files from the front end to the back end. I chose to work with Express and React and I am implementing them on TypeScript. I am using the express-fileupload module to manage the files on the Express App and axios to send http requests. I have wrote Unit Tests for the file function on the back end and it works just fine, so the problem lies on the front end.

This is the function that is supposed to send the files:

async function uploadDatasetFile(formData: FormData): Promise<any> {
  try {
    const response = await axios.post(
      "http://localhost:5000/files/upload",
      formData,
      {headers: {'Content-Type': 'multipart/form-data'}}
    );
    return response.data;
  } catch (error: any) {
    throw error.response.data;
  }
}

This is the query that calls the uploadDatasetFile function:

  const fileMutation = useMutation(uploadDatasetFile);

  const onSubmit: SubmitHandler<DatasetFormValues> = dataset => {
    if (dataset.name && dataset.file) {
      console.log(dataset.file);
      let formData = new FormData();
      formData.append("file", dataset.file);
      formData.append("name", dataset.name);
      fileMutation.mutate(formData);
    }
  };

Finally this is the back end code

    this.app.route('/files/upload')
      .post(
        FilesMiddleware.validateUploadedFile,
        FilesMiddleware.validateRequiredPath,
        FilesController.uploadFile
      );

It doesn't pass the file check and it returns 400. What should I do?


Solution

dataset.file was a FileList actually and I had to change onSubmit to:

  const onSubmit: SubmitHandler<DatasetFormValues> = dataset => {
    if (dataset.name && dataset.file) {
      let formData = new FormData();
      formData.append("file", dataset.file[0]);
      formData.append("name", dataset.name);
      fileMutation.mutate(formData);
    }
  };


Answered By - Iakovos Mastrogiannopoulos
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing