I am working on a music app,how can i upload audio file in my expressjs using cloudinary or any other way?
I tried using thesame format for image upload but didnt work
CodePudding user response:
To upload audio using Express JS, you will need to use the multer middleware. Here is an example of how you can set up the multer middleware and use it to handle audio file uploads:
- First, install the multer package:
npm install multer
- Next, require the multer package in your Express app:
const multer = require('multer')
- Set up the multer middleware by specifying where you want the uploaded audio files to be stored. For example:
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/audio/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
- Use the multer middleware in your route handling function to handle the audio file upload. For example:
app.post('/upload-audio', multer({ storage }).single('audio'), (req, res) => {
// req.file contains the uploaded audio file
// Do something with the audio file, such as save it to a database or storage service
res.send('Audio file successfully uploaded!')
})
- In your HTML form for uploading audio, make sure to include the enctype="multipart/form-data" attribute and specify the name of the file input as audio. For example:
<form action="/upload-audio" method="post" enctype="multipart/form-data">
<input type="file" name="audio" accept="audio/*">
<button type="submit">Upload Audio</button>
</form>
I hope this helps!
CodePudding user response:
To add to Jack's answer, there is a Cloudinary storage engine for Multer you can use to send your files to Cloudinary rather than keeping the assets on disk. https://www.npmjs.com/package/multer-storage-cloudinary