I'm trying to upload a cropped image with Antd upload in React and receive it with multer in express. I'm appending image to formData then posting it with axios. But the multer field is empty. I didn't face any problem in simple file upload. But can't manage with Antd upload.
Here is my React code: API is set up axios. It is working everywhere.
export default class Upload extends Component {
constructor(props) {
super(props)
this.state = {
avatar: [],
loading: true
}
this.onChange = this.onChange.bind(this)
}
onChange(e) {
let formData = new FormData()
formData.append('avatar', e.file)
API.post('/account/avatar', formData, config)
.then(res => {
console.log(res.data)
})
console.log(e.file)
}
render() {
return (
<ImgCrop shape='round'>
<Upload
action={this.onChange}
multiple={false}
showUploadList='false'
onChange={this.onChange}
>
<Button className='upload-avatar-btn'><i className='lnir lnir-pencil'></i></Button>
</Upload>
</ImgCrop>
)
}
Logging e.file in browser's console is giving this:
{lastModifiedDate: 1595920324076, name: "anders-jilden-tcEGBIHm_6E-unsplash.jpg", uid: "rc-upload-1595919951039-2", lastModified: undefined, size: 70585, …}
lastModified: undefined
lastModifiedDate: 1595920324076
name: "anders-jilden-tcEGBIHm_6E-unsplash.jpg"
originFileObj: Blob {lastModifiedDate: 1595920324076, name: "anders-jilden-tcEGBIHm_6E-unsplash.jpg", uid: "rc-upload-1595919951039-2", size: 70585, type: "image/jpeg"}
percent: 100
size: 70585
status: "uploading"
type: "image/jpeg"
uid: "rc-upload-1595919951039-2"
__proto__: Object
Express code:
.post('/avatar', upload.fields([{ name: 'avatar', maxCount: 1 }]), (req, res) => {
const files = req.files.avatar;
console.log(req.files);
console.log(req.files.avatar)
res.send('Uploaded');
})
I'm getting 200 status code in client. But multer is not uploading anything. I have no idea what to do.
console.log(req.files)
is giving this:
[Object: null prototype] {}
First try to wait until upload finished via e.file.status === 'done'
.
After this you can upload the original file object using e.file.originFileObj
.
E.g.:
onChange(e) {
if (info.file.status === 'done') {
let formData = new FormData()
formData.append('avatar', e.file.originFileObj)
API.post('/account/avatar', formData, config)
.then(res => {
console.log(res.data)
})
console.log(e.file)
}
}
This CodeSandBox is good tutorial for using Antd's Upload.
For further inspection of your issue you need to post a minimal reproducable example e.g. as Stackblitz.