1

How upload an image with RTK and Multer ?

JSX file

    const onSubmit = (e) => {
      e.preventDefault();
 
      const payload = new FormData();
      payload.append("imagegif", image);
      payload.append("title", formData.titre);

      addPost(payload);
};

createapi

addPost: build.mutation<"testid", FormData>({
  query: (body) => ({
    url: `posts`,
    method: 'POST',
    body,
  }),
  invalidatesTags: [{ type: 'Post', id: 'LIST' }],
}),

Multer file

const multer = require('multer');

const MIME_TYPES = {
  "image/jpg": "jpg",
  "image/jpeg": "jpg",
  "image/png": "png",
  "image/gif": "gif"
};

const storage = multer.diskStorage({
  destination: '../images/',
  filename: "test.gif"
});

module.exports = multer({ storage: storage }).single("imagegif");

routes

router.post("/", auth,multer,  posts.createPost);

Folder "images is created but no file inside it.

I don't find sample with RTK and file upload.

Nicolas Popy
  • 51
  • 1
  • 7
  • 1
    There is nothing really special regarding RTK and file uploads - fetchBaseQuery is just a wrapper around fetch, so you pretty much do it as you would do it using fetch. There are a few examples for that in this question: https://stackoverflow.com/questions/36067767/how-do-i-upload-a-file-with-the-js-fetch-api – phry Jul 22 '21 at 20:39

1 Answers1

0

payload.append("title", formData.titre);

Maybe not related but, shouldn't be formData.title at least?

Cidwel
  • 45
  • 6
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 19 '22 at 14:25
  • "titre" is "title", at least in e.g. French. – Yunnosch Sep 09 '22 at 06:22