E
E
Emelian19172021-03-15 14:10:45
Express.js
Emelian1917, 2021-03-15 14:10:45

How to send a file using Formdata in React to an Express server in NodeJS?

The page has a form and a button for submitting a file (using React):

const Upload = () => {
const [file, setFile] = useState();

const UploadContent = (event) => {
    event.preventDefault();
    if (event.target.files[0]) {
        setFile(event.target.files[0]);
    }
};

const OnSumbit = (event) => {
    const formData = new FormData();
    formData.append('customFile', file);

    axios.post(
        "http://localhost:3000/upload",
        formData,
        {
            headers: {
                "Content-type": "multipart/form-data"
            },
        }
    )
        .then(res => {
            console.log(`Success` + res.data);
        })
        .catch(err => {
            console.log(err);
        })
}

return <div>
    <h1 style={style}>Зона тестов</h1>
    <input
        accept="video/mp4"
        id="contained-button-content"
        multiple
        type="file"
        onChange={UploadContent}
    />
    <Button variant="contained" color="primary" onClick={OnSumbit}>
        Сохранить и закрыть
    </Button>
</div>


The server uses files-uploader:
app.post('/upload', function(req, res) {
  let sampleFile;
  let uploadPath;

  if (!req.file || Object.keys(req.file).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }

  sampleFile = req.file.customFile;
  uploadPath = __dirname + '/uploads/' + sampleFile.name;

  customFile.mv(uploadPath, function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});


Server response:
604f40692ec00443881883.png

I can not figure out what's wrong, why the file is not loaded. I will be grateful for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Emelian1917, 2021-03-17
@Emelian1917

The problem was in the elementary lack of folders for saving files.
To download files, multer was used and the script for the download module itself looks like this:

const path = require('path');
const multer = require('multer');
const fs = require('fs');

const filePath = {
    common : './content/',
    imageFile: './uploads/images/',
    contentFile: './uploads/content/'
}

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, path.join(__dirname, '.' + filePath[file.fieldname]))
    },
    filename: function (req, file, cb) {
        let name = new Date().toLocaleDateString();
        name = name.replace(':','-');
        let result = name + '-' + file.originalname;
        cb(null, (result))
    }
})

exports.Remove = function (path) {
    try {
        fs.unlinkSync(path);
        console.log('successfully deleted' + path);
    } catch (err) {
        console.log(err);
    }
}

exports.upload = multer({storage: storage}).any();
exports.filePath = filePath;

I have declared file save paths, but I have not given instructions on how to create folders if they are missing according to the code:
common : './content/',
    imageFile: './uploads/images/',
    contentFile: './uploads/content/'

Thus, not finding a way to save, the program shrugged its shoulders and continued to live its own life, not seeing this as a particular tragedy. I have not made any changes in the code yet, I just added folders to the desired path. However, I plan to add a handler so that they are created automatically in the absence.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question