File-Upload using a custom API

I am trying to setup a file upload using the custom apis. First i setup the fileupload-express middleware like this:
import fileUpload from 'express-fileupload'
import { ServerSetupFn } from '@wasp/types'

const serverSetup: ServerSetupFn = async ({ app }) => {
console.log('Setting up server...')
app.use(fileUpload({ createParentPath: true }))
}

export default serverSetup
import fileUpload from 'express-fileupload'
import { ServerSetupFn } from '@wasp/types'

const serverSetup: ServerSetupFn = async ({ app }) => {
console.log('Setting up server...')
app.use(fileUpload({ createParentPath: true }))
}

export default serverSetup
Which is called on startup. (confirmed via the console log statement) But the files and the body property stay empty no matter what.
export const fileUpload = (req, res, context) => {
console.log(req.get('Content-Type'))
console.log(req.body)
console.log(req.files)
res.json({ msg: `Hello, ${context.user?.email || "stranger"}!` })
}
export const fileUpload = (req, res, context) => {
console.log(req.get('Content-Type'))
console.log(req.body)
console.log(req.files)
res.json({ msg: `Hello, ${context.user?.email || "stranger"}!` })
}
Eventho the content type is defined as multipart/form-data and tried this with from within the webapp as well as directly from postman. Any ideas why this might not be working? The webapp code looks like this:
const uploadFile = async (data: FormData) => {
const res = await api.post(`/api/fileupload`, data, { headers: { 'Content-Type': 'multipart/form-data' } })
console.log(res.data)
}

// ...

const onSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
const data = new FormData()
data.append('file', event.currentTarget.file.files[0])
await uploadFile(data)
}
const uploadFile = async (data: FormData) => {
const res = await api.post(`/api/fileupload`, data, { headers: { 'Content-Type': 'multipart/form-data' } })
console.log(res.data)
}

// ...

const onSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()
const data = new FormData()
data.append('file', event.currentTarget.file.files[0])
await uploadFile(data)
}
3 Replies
shayne
shayne2y ago
Hi there @Gwaggli I think the problem here is the app instance available to the setupFn is still using the Wasp default middleware, which sets things like express.json which may be conflicting with your form data middleware. Try using the api keyword (https://wasp-lang.dev/docs/language/features#declaring-an-api-in-wasp) and also set a middlewareConfigFn so you only enable your specific middleware. This example should be pretty close to what you want: https://wasp-lang.dev/docs/guides/middleware-customization#2-customize-api-specific-middleware
Gwaggli
GwaggliOP2y ago
This and updating wasp to the newest version helped fixing the problem. Thank you!
shayne
shayne2y ago
Great, glad it works now!
Want results from more Discord servers?
Add your server