Next.js Discord

Discord Forum

Form-data api route

Unanswered
Yacare Caiman posted this in #help-forum
Open in Discord
Yacare CaimanOP
I feel a bit dumb because this feels like it should be trivial, but I must be overlooking something.
We have a nextjs frontend, where we have a client component that lets users select multiple files to load. We take these files from the client component, send them as form data through an axios post request to the upload-file api route. so it goes client>>api route>>python backend

//client component
const files = new FormData();
input_files.forEach(file => { files.append('files', file); });

The api route gets all files from the form data and sends them through an axios post request to the python backend.

// api route
const data = await request.formData()
const response = await axios.post(apiUrl, { files: data});

with contents + error:
// api route output 
FormData { [Symbol(state)]: [ { name: 'files', value: [File] } ] }
Error: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream



The previous 2 steps are working as far as I can tell, since if we try to send the files from the client component directly to python it works. The python backend needs to receive the files. We've been throwing different ways to get the files from the request, with no luck.
// python backend
@app.route('/file-upload', methods=['POST'])
def get_files():
    files = request.files.getlist('files')


Where are we going wrong? if we try to send the form data directly from the client component it gets sent successfully, but when we try through the api route, it fails. after digging for the last 2 days it seems form data has been a problem for nextjs https://github.com/vercel/next.js/discussions/36153.

7 Replies

Yacare CaimanOP
we are still fighting with this, if any one has any clue, there is something we are not understanding about sending files from route.ts api to python backend
first off dont use axios
Japanese littleneck
I am also stuck at same issue and I use axios either.. @DirtyCajunRice | AppDir what would you suggest instead of axios?
@riský id recommend reading: https://www.adios-axios.com/
Japanese littleneck
thanks mate, will try that out, hopefully it works 🤞
Yacare CaimanOP
so in the end, it looks like the specific problem is Axios + Route. The client component is still sending the data over using Axios (something we might have to change at some point, but nonetheless). What did it was:

in route (where data is a formData object):
const response = await fetch(apiUrl, {
        method: 'POST',
        body: data,
    }).then( response => {
        console.log("response", response.status)
    }).catch( error => {
        console.log("file upload response error", error)
    });

then in the python backend
files = request.files.getlist('files')
@Japanese littleneck fyi