Search code examples
reactjstypescriptaxiosreact-queryexpress-fileupload

How to upload file from frontend to backend


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