I'm attempting to upload an Excel spreadsheet into my React application. I don't need to read it or edit anything, I just need to upload it to a cloud storage location. I've tried using both the standard <input type="file" />
and the react-dropzone
to obtain the file (which it does), however, once I attempt to transfer the file to the back-end using axios
the sent file comes back as undefined
. Here's my code:
Uploader Front-End
import React, { useState, useContext } from 'react';
import FileContext from '../../context/file/fileContext';
const Uploader = () => {
const fileContext = useContext(FileContext);
const { uploadFile } = fileContext;
const [file, setFile] = useState('');
const onChange = (e) => {
setFile(e.target.files[0]);
};
const onSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('file', e.target.files[0]);
uploadFile(formData);
};
return (
<div className="container">
<div className="row">
<form className="col s12" onSubmit={onSubmit}>
<div className="row">
<div className="col s12">
<h4>Upload PO file</h4>
</div>
<div className="input-field col s12">
<label className="active" htmlFor="xlsFile">
Choose an XLS/XLSX file to upload...
</label>
<input
type="file"
name="xlsFile"
id="xlsFile"
accept=".xls, .xlsx"
onChange={onChange}
/>
</div>
<div className="col s12">
<button className="btn btn-primary">Upload</button>
</div>
</div>
</form>
</div>
</div>
);
};
export default Uploader;
uploadFile()
function
const uploadFile = async (formData) => {
const uploaded = await axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
};
Router POST for File Upload
router.post('/upload', async (req, res) => {
const { file } = req.files;
console.log(file);
});