javascript 使用Multer时出现内部服务器错误(node.js)

2izufjch  于 2022-11-20  发布在  Java
关注(0)|答案(2)|浏览(131)

我正试图上传图像使用multer,通过以下youtube教程。但不能理解为什么它不能正常工作。
密码:
index.html

<body>

<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="image">
    <input type="submit">
</form>

</body>

server.js

const path = require('path');
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

app.use(express.static(path.join(__dirname,"../public")));

const multer=require('multer');

const storage=multer.diskStorage({
    destination:(req,file,cb)=>{
        cb(null,"./Images")
    },
    filename: (req,file,cb)=>{
        console.log(file)
        cb(path.extname(file.originalname));
        console.log("---")
    }
});

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

app.post("/upload",upload.single('image'),(req,res)=>{

    console.log("up")
});

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname,'../public/index.html'));
  });

server.listen(3000, () => {
  console.log('listening on *:3000');
});

记录档:

listening on *:3000
{
  fieldname: 'image',
  originalname: 'vidLogo.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg'
}
---

如您所见,日志一直生成到最后。
服务器抛出内部服务器错误(500)并发送响应文件,如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>.jpg</pre>
</body>
</html>
ddhy6vgd

ddhy6vgd1#

  • 在server.js中,检查当前目录,然后移动到“Images”文件夹
  • 检查“Images”文件夹是否存在于项目的正确路径中
  • 在目的地末尾添加“/”

在此情况下,您可以使用以下命令:

  • 将错误参数添加到回调函数:cb(错误可以为空)
const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, `${process.cwd()}/Images/`); // destination
  },
  filename(req, file, cb) {
     cb(
      null,
      `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}` // filename
     );
  },
});

通过上传文件进行高级验证的完整示例

import path from "path";
import express from "express";
import multer from "multer";
import asyncHandler from "express-async-handler";
import process from "process";

const router = express.Router();

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, `${process.cwd()}/uploads/documents/`);
  },
  filename(req, file, cb) {
    cb(
      null,
      `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
    );
  },
});

function checkFileType(file, cb) {
  const extensionsAutorisees = [
    "text/plain",
    "application/pdf",
  ];

  if (extensionsAutorisees.includes(file.mimetype)) {
    return cb(null, true);
  } else {
    return cb(
      new Error(`Only documents of type PDF, Text are authorized`)
    );
  }
}

const upload = multer({
  storage,
  limits: {
    fileSize: 1024 * 1024 * 5, // 5Mb file size limit
  },
  fileFilter: function (req, file, cb) {
    checkFileType(file, cb);
  },
}).single("document");

router.route("/").post(
  protect,
  asyncHandler(async (req, res) => {
    upload(req, res, async (err) => {
      if (
        err &&
        err.name &&
        err.name === "MulterError" &&
        err.code == "LIMIT_FILE_SIZE"
      ) {
        return res.status(400).send({
          error: err.name,
          message: `Document too large, the maximum size is 5Mb`,
        });
      }

      // handle other errors
      if (err) {
        return res.status(500).send({
          error: "FILE UPLOAD ERROR",
          message: `Document loading error : ${err.message}`,
        });
      }

      return res.status(201);

    });
  })
);
iszxjhcz

iszxjhcz2#

该错误位于filename函数内的第二个回调中,在该函数中,您需要提供null作为错误,并提供文件名作为值:cb(null, path.extname(file.originalname));
尝试如下更新代码:

const storage=multer.diskStorage({
    destination:(req,file,cb)=>{
        cb(null,"./Images")
    },
    filename: (req,file,cb)=>{
        console.log(file)
        // I updated the file name as well so that it is not extension only
        cb(null, file.fieldname + path.extname(file.originalname)); // <--- HERE
        console.log("---")
    }
});

相关问题