File upload to server from Next js API

Viewed 373

I am trying to upload an image to the server from Next js API. My codes is :

Getting an image to Next API form react form :

Next js form :

const handleImgChange = (e) => {
    if (e.target.files && e.target.files[0]) {
        const img = e.target.files[0];
        setProfileImg(img);
    }
};
const handleOnsubmlit = (e) => {
    e.preventDefault();
    const data = new FormData();
    data.append("profile_picture", profileImg);

    fetch(`${NEXT_URL}/api/imageupload`, {
        method: "PUT",
        body: data,
    })
    .then((response) => response.json())
    .then((data) => {
       console.log(data);
    })
    .catch((error) => {
       console.error(error);
    });
};

Next js API:

export const config = {
  api: {
    bodyParser: false,
  },
};

const asyncParse = (req) =>
  new Promise((resolve, reject) => {
    const form = new IncomingForm({ multiples: true });
    form.parse(req, (err, fields, files) => {
        if (err) return reject(err);
        resolve({ files });
    });
});

export default async (req, res) => {
 if (req.method === "PUT") {
    if (!req.headers.cookie) {
        res.status(403).json({ message: "Not Authorized" });
        return;
    }
    const { token } = cookie.parse(req.headers.cookie);
    const result = await asyncParse(req);

    const config = {
        headers: {
            "Content-Type": "multipart/form-data",
            Authorization: `Bearer ${token}`,
        },
    };

    const restApiRes = await axios.put(`${API_URL}/user/settings`, 
      { profile_picture: result.files.profile_picture }, 
      config);

    if (restApiRes.ok) {
        res.status(200).json(restApiRes.data);
    } else {
        res.status(403).json({ message: "User forbidden" });
    }
  } else {
    res.setHeader("Allow", ["PUT"]);
    res.status(405).json({ message: `Method ${req.method} not allowed` });
  }
};

I got the response but is not changing. I think there is an issue with my image parsing or sending. Can anyone help? Thanks in advance.

0 Answers
Related