Next.js Discord

Discord Forum

File upload from Client to Server

Answered
American Crocodile posted this in #help-forum
Open in Discord
American CrocodileOP
I have an API which I access only from the server side. This API accepts a base64 string for some file uploads. I'm wondering what my options are for getting the files or strings from client side over to server side.
On client side I'm using the react=dropzone library for drag and drop capabilities in the file upload. It currently grabs the files and puts it into a state.
While there is an input tag in the component the files do not seem to exist there for any amount of time so a form with action is not working.

I have this file upload appearing in a server side modal, so I was hoping to initiate the upload from the server component wrapping the dropzone component, but that is not neccesary.
I was thinking about passing into it a server action, maybe change it to string client side so it can be serialized over to server there.
Answered by Cape lion
You can create a new FormData object and append the files to it using the append method. Then, you can send the FormData object via AJAX using the XMLHttpRequest object or the fetch API.
View full answer

4 Replies

Cape lion
You can create a new FormData object and append the files to it using the append method. Then, you can send the FormData object via AJAX using the XMLHttpRequest object or the fetch API.
Answer
Cape lion
For example,
const formData = new FormData(); formData.append('file', file); fetch('/api/upload', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
On the server side, you can access the files using the files property of the request object.
const multer = require('multer'); const upload = multer(); app.post('/api/upload', upload.single('file'), (req, res) => { const file = req.file; // do something with the file });