Closed sooooooooooooooooootheby closed 5 months ago
I bump into the same issue using pinia store for input file
I manage rewritng a ref()
input (called inputFile) with and set the name of the input in <template></template>
tag as name="file"
here is what i have done in front end app :
`<template>
<div class="form_control">
<label for="image">Image</label>
<input
type="file"
id="image"
name="file" // <-- here
accept="image/png, image/jpeg, image/webp"
ref="inputFile" // <-- here
/>
</div>
</template>`
script
`<script setup>
import { ref } from 'vue'
const inputFile = ref(null) <-- Here
async function createPost() {
const myInputFile = inputFile.value //reactivity fundamentals
//send img post
const image = await primarimageapi(myInputFile)
}
</script>`
On the api function primarimageapi i make this:
`export const primarimageapi = async (myInputFile) => {
try {
const file = myInputFile.files[0] <-- Here File Grabbed
//formData instance
const formData = new FormData()
//add element
formData.append('file', file)
const prePostImg = await fetch(`${base_url}/post/image/create`, {
method: 'POST',
body: formData
})
.then((res) => res.json())
.then((newres) => newres.image_url)
return prePostImg
} catch (err) {
console.log(err)}}`
my blog-app three elements was organized like below:
`blog*app --|
|
|* \_ _client
|
|
|_ \_ _server
|
|_ _src
|
|_ _public
| |
| |_ _images
|
|
|_ _routes
|
|_ \_post-routes.js (file)`
In post-route.js
file i wrote this :
//multer
`const storage = multer.diskStorage({destination: function (req, file, callback) {
callback(null, path.join(__dirname, "../public/images"));
},
filename: function (req, file, callback) {
const filename = `${file.fieldname}_${Date.now()}${path.extname(
file.originalname
)}`;
callback(null, filename);},
})
const upload = multer({
storage: storage,
limits: { fileSize: 1000000 },
});
`
//middleware destination image - express
`router.use(`/images`, express.static(path.join(__dirname, "../public/images")))`
//router
`router.post("/image/create", upload.single("file"), (req, res) => {
try {
const base_url = process.env.API_URL;
res.status(200).json({
success: true,
image_url: `/${base_url}/images/${req.file.filename}`,
});
} catch (err) {
console.log(err);
}
})`
then i obtain inside src/public/images
my first image : file_1717587794699.jpg
Looking your code, I found that the problem was in my middleware. now, The problem was solved. thank you and your code.
There is nothing error with using html forms, but requests made through pinia will get 'MulterError: Unexpected field att wrappedFileFilter'