How could I use A Multipart-Form In Next.js using API Routes with Django in back end #36153
Replies: 4 comments 17 replies
-
Next.js API routes run in Node.js, which doesn't support FormData, so you need a way to create those. Setting the content type won't cut it because multipart-form streams are a special kind of format. See in the browser that the outgoing request has content type This sort of thing is best to be handled by a package, for example https://www.npmjs.com/package/form-data, because of all edge cases that need to be handled. I also think you don't need to specify the content type, |
Beta Was this translation helpful? Give feedback.
-
The following steps works for me:
import axios from "axios";
const baseURL = process.env.PHOTO_ADDRESS || "http://photo.default/v1";
const apikey = process.env.PHOTO_API_KEY;
export const config = {
api: {
bodyParser: false,
},
};
async function handler(req, res) {
let uploadPhotoAddress = baseURL + "/upload";
if (req.method == "POST") {
const { data } = await axios.post(uploadPhotoAddress, req, {
responseType: "stream",
headers: {
"Content-Type": req.headers["content-type"], // which is multipart/form-data with boundary included
apikey,
},
});
data.pipe(res);
} else {
return res.status(405).json({ message: "Method Not Allowed" });
}
}
export default handler; |
Beta Was this translation helpful? Give feedback.
-
Hi there, Here's one more good solution w/o using any external packages. That works for me:
|
Beta Was this translation helpful? Give feedback.
-
This code works on my laptop without Axios and any external packages.
|
Beta Was this translation helpful? Give feedback.
-
I'm using Django Rest As A back end server , what i'm trying to do is posting data that contains a file (ex : {first_name:"", last_name: "", profile_picture:}) through nextjs api to my
django
server . what i found is that theFormData
is not defined in api routes files , and even if i add content-type:"multipart/form-data" is not workingi tried to use third party package such as formidable but without any result
check out the screen below
i will be appreciated for your help to
Beta Was this translation helpful? Give feedback.
All reactions