收到此错误:错误:表格意外结束

问题描述 投票:0回答:0

当尝试从前端向后端提交音频文件时,我收到两个错误错误:错误:表单意外结束 错误:上传文件:错误:上传音频文件失败 我使用表单数据在前端发送音频文件,在后端使用 multer 和 gridfs。有人知道我为什么会收到这个错误吗?

当尝试从前端向后端提交音频文件时出现此错误:错误:表单意外结束,我使用表单数据在前端发送音频文件,在后端使用 multer 和 gridfs。有人知道我为什么会收到这个错误吗?

here is my app.js 
import React, { useState } from 'react';

const App = () => {
  const [selectedFile, setSelectedFile] = useState(null);

  const handleFileChange = (event) => {
    setSelectedFile(event.target.files[0]);
  }

  const handleFormSubmit = (event) => {
    event.preventDefault();

    const formData = new FormData();
    formData.append('audioFile', selectedFile);

    fetch('http://localhost:4002/audio', {
      method: 'POST',
      body: formData,
    })
    .then(response => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error('Failed to upload audio file');
      }
    })
    .then(data => {
      console.log('File uploaded successfully:', data);
      // Do something with the response data
    })
    .catch(error => {
      console.error('Error uploading file:', error);
    });
  }

  return (
    <div className="flex h-[100vh] w-[100%] items-center justify-center">
      <form onSubmit={handleFormSubmit} encType="multipart/form-data">
        <input type="file" onChange={handleFileChange} />
        <button type="submit" disabled={!selectedFile}>Upload</button>
      </form>
    </div>
  );
};

export default App;

here is my sever.js
const express = require('express');
const mongoose = require('mongoose');
const multer = require('multer');
const { GridFsStorage } = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const cors = require('cors');
const path = require('path')
const bodyParser = require("body-parser")

const app = express();
app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));

mongoose.connect('mongodb+srv://jordandeeds31:[email protected]/?retryWrites=true&w=majority', {
    useUnifiedTopology: true,
    useNewUrlParser: true,
}).then(() => {
    console.log('Connected to MongoDB');
}).catch((err) => {
    console.error(err);
});

const conn = mongoose.connection;
let gfs;

conn.once('open', () => {
    gfs = Grid(conn.db, mongoose.mongo);
    gfs.collection('audioFiles');
});

const storage = new GridFsStorage({
    url: 'mongodb+srv://jordandeeds31:[email protected]/grid?retryWrites=true&w=majority',
    file: (req, file) => {
        return {
            filename: file.originalname,
            bucketName: 'audioFiles'
        };
    }
});

const upload = multer({
    storage: storage,
    limits: {
        fileSize: 90 * 1024 * 1024 // 10MB
    },
    fileFilter: (req, file, cb) => {
        if (file.mimetype.startsWith('audio/')) {
            cb(null, true);
        } else {
            cb(new Error('File type not supported.'));
        }
    }
});

// Add this middleware before the POST route
app.use(upload.any());

const audioFileSchema = new mongoose.Schema({
    fileUrl: {
        type: String,
        required: true
    },
    audioData: {
        type: Buffer,
        required: true
    }
});

const AudioFile = mongoose.model('AudioFile', audioFileSchema);

app.post('/audio', upload.single('audioFile'), async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ message: 'No file uploaded.' });
        }

        const audioFile = new AudioFile({
            fileUrl: `http://localhost:4002/audio/${req.file.filename}`,
            audioData: req.file.buffer
        });

        console.log('req.file.buffer:', req.file.buffer);

        const savedAudioFile = await audioFile.save();
        res.json({ fileUrl: savedAudioFile.fileUrl });
    } catch (err) {
        console.error(err);

        if (err instanceof multer.MulterError) {
            res.status(400).json({ message: 'File upload error.' });
        } else if (err.message === 'File type not supported.') {
            res.status(400).json({ message: err.message });
        } else {
            res.status(500).send('Internal Server Error');
        }
    }
});


app.get('/audio/:filename', (req, res) => {
    const { filename } = req.params;
    const readStream = gfs.createReadStream({ filename });

    readStream.on('error', (err) => {
        console.error(err);
        res.status(404).send('File not found.');
    });

    readStream.pipe(res);
});

app.listen(4002, () => {
    console.log('Listening on port 4002');
});
node.js reactjs multer gridfs multer-gridfs-storage
© www.soinside.com 2019 - 2024. All rights reserved.