I am unable to upload file using FormData using axios from React application to express Server which uses multer.
Text data appended in formData shows up on server but any file seems to be not visible on server side.
exploring formData keys on client side shows the file though.
Here is my server code to print the contents of body: postFile.ts
import * as path from 'path';
let multer = require("multer");
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, path.resolve(__dirname));
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
let upload = multer({ storage: storage });
export const postFile = (app: IApp) => {
app.post('/uploadFile', upload.any(), (request: IRequest, response: IResponse) => {
console.log('Got body:', JSON.stringify(request.body));
response.sendStatus(200);
});
}
This is the React client side code: filePicker.tsx
import axios from "axios";
import * as React from "react";
interface IFilePickerProps {
fileToUpload: File;
setFileToUpload: React.Dispatch<File | undefined>;
}
export const FilePicker = (props: IFilePickerProps) => {
const { setFileToUpload, fileToUpload } = props;
// Ref to input element to reset value on file upload completion
const inputRef = React.useRef<HTMLInputElement>();
const { onFileUpload, onFileChange } = useUploadFileCallbacks(
setFileToUpload,
fileToUpload,
inputRef
);
return (
<>
<label>
<input type="file" onChange={onFileChange} ref={inputRef} />
</label>
<button onClick={onFileUpload}>Upload File</button>
</>
);
};
const useUploadFileCallbacks = (
setFileToUpload: React.Dispatch<File | undefined>,
fileToUpload: File,
inputRef: React.RefObject<HTMLInputElement>
) => {
const onFileChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setFileToUpload(event.target.files[0]);
},
[setFileToUpload]
);
const onFileUpload = React.useCallback(() => {
handleFileUpload(fileToUpload, inputRef);
}, [fileToUpload]);
return { onFileChange, onFileUpload };
};
const handleFileUpload = async (
fileToUpload: File,
inputRef: React.RefObject<HTMLInputElement>
) => {
let formData = new FormData();
formData.append("usernamesss", "Sparsha Saha");
formData.append("file", fileToUpload);
axios
.post("http://localhost:3001/uploadFile", formData, {
headers: {
"content-type": "multipart/form-data",
},
})
.then(() => {
console.log("Complete");
});
inputRef.current.value = "";
};
The console.log in postFile.ts only shows 'usernamesss: Sparsha Saha'
I have looked around for solutions but nothing seems to work for me. Can someone please help me out?
It seems like, console.log does not show the file but it definitely gets uploaded to the designated folder. I wonder which part of the request the file data actually gets appended to and whether we can visualise it in some way.