expressjs / multer

Node.js middleware for handling `multipart/form-data`.
MIT License
11.56k stars 1.05k forks source link

Error while uploading Image and Video File together ! #1180

Open Znoy108x opened 1 year ago

Znoy108x commented 1 year ago

Form Data image

This is the code to upload image and upload video ` const imageStorage = multer.diskStorage({ destination: "./assets/Images", filename: (req, file, cb) => { cb( null, "Image-" + file.originalname.split(".")[0] + "-" + Date.now() + "." + file.originalname.split(".")[1] ); }, }); const upload_image = multer({ storage: imageStorage, limits: { fileSize: 10000000, }, fileFilter(req, file, cb) { if (!file.originalname.match(/.(png|jpg|JPG|PNG|webp|WEBP)$/)) { return cb(new Error("Only Png / Jpg / Webp format is accepted")); } cb(undefined, true); }, });

const videoStorage = multer.diskStorage({ destination: "./assets/Videos", filename: (req, file, cb) => { cb( null, "Video-" + file.originalname.split(".")[0] + "-" + Date.now() + "." + file.originalname.split(".")[1] ); }, }); const upload_video = multer({ storage: videoStorage, limits: { fileSize: 100000000, }, fileFilter(req, file, cb) { if (!file.originalname.match(/.(mp4|mov)$/)) { return cb(new Error("Only mp4 / mov format is accepted")); } cb(undefined, true); }, }); `

Code of the request router.post( "/add-image-video-post", upload_image.fields([{ name: "Image", maxCount: 1 }]), upload_video.fields([{ name: "Video", maxCount: 1 }]), async (req, res) => { console.log(req.files); return res.status(200).json({ success: true }); } ); Error Image image

Error Text Error: Unexpected end of form at Multipart._final (C:\Users\Hp\Desktop\twitter\backend\node_modules\busboy\lib\types\multipart .js:588:17) at callFinal (node:internal/streams/writable:694:27) at prefinish (node:internal/streams/writable:723:7) at finishMaybe (node:internal/streams/writable:733:5) at Multipart.Writable.end (node:internal/streams/writable:631:5) at onend (node:internal/streams/readable:693:10) at processTicksAndRejections (node:internal/process/task_queues:78:11)

barbiedo commented 1 year ago

Same error too.that the error says no file uploaded. As I click the upload button

Upload photo code const express = require('express'); const multer = require('multer'); const path = require('path');

const app = express(); const port = process.env.SERVER_PORT || 3000;

// Set up storage for uploaded files const storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, '../assets/uploads'); }, filename: function (req, file, cb) { const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9); const fileExtension = path.extname(file.originalname); cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension); } });

const upload = multer({ storage: storage });

// Serve uploaded files statically app.use('/uploads', express.static('uploads'));

// Handle file upload app.post('/upload-photo', upload.single('image'), (req, res) => { if (!req.file) { return res.status(400).json({ message: 'No file uploaded' }); }

// You can perform additional logic here, like saving the file path to a database // and returning a response. const { DB_CURRENT_TIMESTAMP, queryDb } = require('@api/utils/mysql');

module.exports = async function(req, res) { try { const { image = '' } = req.body;

if (!image) { return res.status(400).json({ message: 'Please select an Image.', }); }

const imagePath = /uploads/${image.filename}; // Update the path to match your file storage location

// Save file path to the database await queryDb( INSERT INTO gallery (date_uploaded, image) VALUES (?, ?), [DB_CURRENT_TIMESTAMP, imagePath] );

return res.status(200).json({ message: 'Image Uploaded!' }); } catch (err) { res.status(500).json({ message: Server error : ${err.message} }); } };

res.status(200).json({ message: 'Image Uploaded' }); });

app.listen(port, () => { console.log(Server is running on port ${port}); });

const { DB_CURRENT_TIMESTAMP, queryDb } = require('@api/utils/mysql');

module.exports = async function(req, res) { try { var { // event_id = '', // photo_name = '', image = '', } = req.body; // var image = req.files && req.files.image;

  if (!image) {
      return res.status(400).json({
        message: 'Please select an Image.',
      });
  }
  // if (!event_id) {
  //     return res.status(400).json({
  //       message: 'Please provide the event Id.',
  //     });
  // }
  // if (!photo_name) {
  //     return res.status(400).json({
  //       message: 'Please provide a name for the photo.',
  //     });
  // }

  await queryDb(`
      INSERT INTO gallery (date_uploaded, image ) VALUES (?,?)`,
      [ DB_CURRENT_TIMESTAMP, image ]
  );

  return res.status(200).json ({
      message: 'Photo successfully added!'
  });

} catch(err) { // console.log(err.message); res.status(500).json({ message: Server error : ${err.message} }); } }