【发布时间】:2021-08-27 02:18:29
【问题描述】:
我是 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>
【问题讨论】:
标签: angular frontend backend mean image-upload