Stack Overflow Asked by Jass Preet on January 8, 2021
I am using this library for file uploading. Here it says
sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
But I want to use this using await and async so when I try like
router.put("/upload", async(req,res)=>{
const isUploaded = await sampleFile.mv('/somewhere/on/your/server/filename.jpg');
console.log(isUploaded) // it gives me undefined over here.
});
I have gone through the code of .mv() of the library that you are using. It does have promise support.
However, it seems like it resolves() with empty argument.
So, if you want to use async await, you can use,
router.put("/upload", async(req,res)=>{
try{
await sampleFile.mv('/somewhere/on/your/server/filename.jpg');
res.send('File uploaded!');
} catch(err){
res.status(500).send(err);
});
You cannot use
const isUploaded = await mvPromise('/somewhere/on/your/server/filename.jpg');
It will always be undefined because it does not return anything.
Correct answer by Rupjyoti on January 8, 2021
Library supports promises when no callback is provided so you should be able to just await it
To access the proper file create in middleware you need to look at the request. Also the response of the function mv
is not supposed to return anything. As long as it doesn't throw then you're good to go.
app.post("/upload", async (req, res) => {
if (!req.files || Object.keys(req.files).length === 0) {
return res.status(400).send("No files were uploaded.");
}
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let { sampleFile } = req.files;
// Use the mv() method to place the file somewhere on your server
try {
await sampleFile.mv("/somewhere/on/your/server/filename.jpg");
res.send("File uploaded!");
} catch (e) {
res.sendStatus(500);
}
});
Answered by Edward Romero on January 8, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP