Reputation: 358
I'm currently uploading an image and data using two calls to the server and I want to reduce this to one call to the server.
My current front end code as follows. The input field is :
<input
required
type="file"
onChange={this.fileUploaded}
/>
Uploading to state using this code:
userEvent.image = new FormData()
userEvent.image.append('file', e.target.files[0])
this.setState({ userEvent })
Sending to backend using this code:
let data = this.state.userEvent.image
let eventData = this.state.userEvent
eventData.token = localStorage.getItem("token")
axios.post(`${process.env.REACT_APP_API}/image`, data)
.then(res => {
axios.patch(`${process.env.REACT_APP_API}/events/${res.data._id}`, eventData)
.then(res => {console.log(res)})
.catch(err =>{console.log(err)})
})
.catch(err => {
console.log("imgerr", err)
})
and my backend code (for the first call to the server) is:
const Event = require('../models/events')
module.exports = (req, res) => {
let apiUrl = req.protocol + '://' + req.get('host') + '/'
let newEvent = {
imageURL: apiUrl + req.file.filename,
}
Event.create(newEvent)
.then(data => {
console.log('data', data)
res.send(data)
})
.catch(err => console.log(err))
}
When I try sending the image and the data in the one object, I get an error at the backend because req.file is undefined when I do this.
What am I missing?
Upvotes: 0
Views: 645
Reputation: 358
I figured it out.
I appended the other data that I had saved in state that I also wanted to send to the backend.
Arrays of objects need to be stringified.
let userEvent = this.state.userEvent
console.log('userEvent.ticekts', userEvent.tickets);
let data = userEvent.image
data.append('title', userEvent.title)
data.append('venue', userEvent.venue)
data.append('description', userEvent.description)
data.append('startDetails', userEvent.startDetails)
data.append('endDetails', userEvent.endDetails)
data.append('token', localStorage.getItem("token"))
data.append('currency', userEvent.currency)
data.append('lat', userEvent.lat)
data.append('lng', userEvent.lng)
data.append('address1', userEvent.address1)
data.append('address2', userEvent.address2)
data.append('address3', userEvent.address3)
data.append('address4', userEvent.address4)
data.append('eventPassword', userEvent.eventPassword)
data.append('globalRefundPolicy', userEvent.globalRefundPolicy)
data.append('globalRefundOptions', JSON.stringify(userEvent.globalRefundOptions))
data.append('region', userEvent.region)
data.append('tickets', userEvent.tickets)
data.append('ticketTypesEquivalent', userEvent.ticketTypesEquivalent)
userEvent.tickets.forEach(item => {
data.append(`tickets[]`, JSON.stringify(item));
});
axios.post(`${process.env.REACT_APP_API}/image`, data)
.then(res => {
console.log('res', res)
})
.catch(err => {
console.log("imgerr", err)
})
Upvotes: 1