2301_79683887 2024-10-17 21:33 采纳率: 70.6%
浏览 91

express 文件上传错误error: unexpected end of form



// 确保上传目录存在
const uploadDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

// 设置文件存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, uploadDir);
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});

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

// 上传音乐文件
router.post('/upload', upload.fields([{ name: 'audioFile' }, { name: 'coverImage' }]), async (req, res) => {
  try {
    if (!req.files.audioFile) {
      throw new Error('No audio file uploaded');
    }

    const audioFile = req.files.audioFile[0];
    const coverImageFile = req.files.coverImage ? req.files.coverImage[0] : null;

    const { originalname, filename: audioFileName } = audioFile;
    const title = Buffer.from(originalname, 'latin1').toString('utf8').split('.').slice(0, -1).join('.');

    const audioFilePath = `http://localhost:3001/uploads/${audioFileName}`;
    const coverImagePath = coverImageFile ? `http://localhost:3001/uploads/${coverImageFile.filename}` : null;

    console.log('File uploaded:', audioFile); // 添加日志记录

    const newSong = await Song.create({
      title,
      artist: req.body.artist || 'Unknown', // 可以根据需要修改
      path: audioFilePath,
      coverImagePath: coverImagePath,
      coverImage: coverImageFile ? fs.readFileSync(coverImageFile.path) : null,
      audioData: fs.readFileSync(audioFile.path),
      lyrics: null
    });

    res.status(200).json({ message: 'File uploaded successfully', song: newSong });
  } catch (error) {
    console.error('Error uploading song:', error); // 添加错误日志
    res.status(500).json({ error: 'Failed to upload song' });
  }
});

报错图片

img

  • 写回答

1条回答 默认 最新

  • 无疆76 2024-10-17 21:34
    关注

    以下回复参考:皆我百晓生券券喵儿等免费微信小程序作答:

    你遇到的问题是关于Express和Multer文件上传时的错误,"unexpected end of form"。这种错误可能是由于请求未完全发送完成或者文件不符合预期的格式导致的。为了解决这个问题,你可以尝试以下几个步骤:

    1. 确保前端发送请求时正确设置了内容类型(Content-Type)为multipart/form-data。Multer要求请求的Content-Type必须设置为multipart/form-data才能正常工作。
    2. 检查前端上传文件的代码是否正确。确保前端正确发送了文件和其他表单字段。确保使用正确的HTTP请求方法(POST)并设置了正确的表单边界(boundary)。边界对于识别表单字段之间的分隔符非常重要。
    3. 检查你的后端路由是否正确处理了文件上传请求。确认你使用了正确的中间件(如multer)来处理文件上传。确认上传的文件大小是否超过了服务器或Multer的限制,导致请求在处理过程中被中断。检查服务器是否能够正确处理不同类型的文件,避免因文件格式不匹配导致的问题。
    4. 如果你在请求中包含多个文件字段(如audioFile和coverImage),请确保每个字段都有相应的名称和文件名设置正确。在Multer的配置中,检查filename函数是否正确返回文件名。确保文件名不包含非法字符或路径不正确。
    5. 检查服务器端的日志输出,查看是否有更多关于错误的详细信息。检查是否有其他中间件或插件干扰了文件上传过程。有时候,其他中间件可能会修改请求体或响应头,导致Multer无法正确解析请求。

    如果以上步骤都没有解决问题,你可能需要进一步检查你的代码和环境配置。可以尝试使用其他工具(如Postman)测试文件上传功能是否正常工作,排除是前端问题还是后端问题。如果问题仍然存在,请提供更多的代码和错误信息,以便更好地分析和解决问题。

    评论

报告相同问题?

问题事件

  • 创建了问题 10月17日