Next.js Discord

Discord Forum

Handling media uploads with server actions

Answered
English Angora posted this in #help-forum
Open in Discord
English AngoraOP
I am new in Nextjs please tell me how to handle media uploads with server actions Nextjs docs not tell that
Answered by B33fb0n3
well, you needed to have a form, to have formdata, but there is no form. So you can go the way via a route handler, to upload the file through your own route handler. Because you have the buffer
View full answer

16 Replies

that depends on your storage provider how to upload data to it. If you know how you upload files to your storage provider, just call the sdk/api endpoint and provide the data. If you are using S3 from AWS I can help you further 🙂 @English Angora
English AngoraOP
you mean first i send formdata from client component or server component to server actions and then send formdata to api endpoint ?
yes, because normally you don't want that the client has the secret keys to upload media
English AngoraOP
i am using custom select input not native select, Can server action pick custom select input value in formData
is your custom file input in the background an input field? It's just styled custom?
English AngoraOP
i am using mui select component i checked and not find input field
can you share me a link to the docs please
English AngoraOP
there isn't any file upload. You are right.
English AngoraOP
i am using both select component and npm package react-dropzone
ah ok, than you can use the onDrop function from react-dropzone:
const onDrop = useCallback((acceptedFiles) => {
    acceptedFiles.forEach((file) => {
      const reader = new FileReader()

      reader.onabort = () => console.log('file reading was aborted')
      reader.onerror = () => console.log('file reading has failed')
      reader.onload = () => {
      // Do whatever you want with the file contents
        const binaryStr = reader.result
        console.log(binaryStr)
      }
      reader.readAsArrayBuffer(file)
    })
    
  }, [])

You can see, that you get the buffer and you want to send the buffer to your backend and from there you can access your secret keys to upload your files to your storage provider. It would be a little easier with the normal file upload from https://mui.com/material-ui/react-button/#file-upload but like the way you want to go is also possible
English AngoraOP
how i achieve this with formData and server actions
well, you needed to have a form, to have formdata, but there is no form. So you can go the way via a route handler, to upload the file through your own route handler. Because you have the buffer
Answer
English AngoraOP
thankyou so much @B33fb0n3
cool, please mark solution