加载资源失败:服务器响应状态为 500(内部服务器错误)当我尝试上传图像时出现此错误

Failed to load resource: the server responded with a status of 500 (Internal Server Error) this error occurs when I try to upload an image

我是 MEAN 开发的新手。我有两个输入字段和一个带有照片上传按钮的字段。虽然我设法在屏幕上显示上传的照片,但在将其上传到服务器时遇到问题。有人可以帮忙吗?

我也遇到这个错误:

Error: ENOENT: no such file or directory, open 'C:\Something\Something\Something\Practice\finalappbackend\backedn\images\title-i-entered-1623300156286.jpeg'

这是我的后端代码:

app.js

const multer = require("multer");

const MIME_TYPE_MAP = {
  "image/png": "png",
  "image/jpeg": "jpeg",
  "image/jpg": "jpg",
};

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const isValid = MIME_TYPE_MAP[file.mimetype];
    let error = new Error("Invalid mime type");
    if (isValid) {
      error = null;
    }
    cb(error, "backedn/images");
  },
  filename: (req, file, cb) => {
    const name = file.originalname.toLowerCase().split(" ").join("-");
    const ext = MIME_TYPE_MAP[file.mimetype];
    cb(null, name + "-" + Date.now() + "." + ext);
  },
});


app.post(
  "/api/posts",
  multer({ storage: storage }).single("image"),
  (req, res, next) => {
    const post = new Post({
      title: req.body.title,
      content: req.body.content,
    });
    console.log(post);
    post.save().then((result) => {
      res.status(201).json({
        message: "Post added successfully",
        postId: result._id,
      });
    });
  }
);

这是我在前端的代码:

posts.service.ts

addPost(id: string, title: string, content: string, image: File) {
    const postData = new FormData();
    postData.append("title", title);
    postData.append("content", content);
    postData.append("image", image, title);
    this.http
      .post<{ message: string; postId: string }>(
        'http://localhost:3000/api/posts',
        postData
      )
      .subscribe((responseData) => {
        const post: Post = {id: responseData.postId, title: title, content: content}
        this.posts.push(post);
        this.postsUpdated.next([...this.posts]);
      });
  }


post-create.component.ts

imagePreview: string | ArrayBuffer;

onImagePicked(event: Event) {
    const file = (event.target as HTMLInputElement).files[0];
    this.form.patchValue({ image: file });
    this.form.get('image').updateValueAndValidity();
    const reader = new FileReader();
    reader.onload = () => {
      this.imagePreview = reader.result;
    };
    reader.readAsDataURL(file);
  }


onSavePost() {
    if (this.form.invalid) {
      return;
    }
    if (this.mode === 'create') {
      this.postsService.addPost(
        this.form.value.id,
        this.form.value.title,
        this.form.value.content,
        this.form.value.image
      );
    } else {
      this.postsService.updatePost(
        this.postId,
        this.form.value.title,
        this.form.value.content
      );
    }

    this.form.reset();
  }

和post-create.component.html


<div>
      <button mat-stroked-button type="button" (click)="filePicker.click()">
        Pick Image
      </button>
      <input type="file" #filePicker (change)="onImagePicked($event)" />
</div>

解释一下

ENOENT 代表:错误无条目。如果你看错误:

Error: ENOENT: no such file or directory, open 'C:\Something\Something\Something\Practice\finalappbackend\backedn\images\title-i-entered-1623300156286.jpeg'

意思是:我无法打开'...finalappbackend\backedn\images'来保存图片,因为这个目录不存在

multer npm page

Note: You are responsible for creating the directory when providing destination as a function. When passing a string, multer will make sure that the directory is created for you.

动作

确保目录已创建。可能是名称中的拼写错误 backedn