javascript - 如何让我的控制器发布以在前端 vus js 和后端 nodejs 中使用 multer npm 处理文件我不会在后端恢复文件?
问题描述
这里是后端,它总是告诉我未定义找到文件
const mysql = require("mysql");
const Poste = require("../models/post");
// Create and Save a new Poste
exports.create = (req, res) => {
res.json({
file: `${req.protocol}://${req.get("host")}/images/${req.file}`,
});
console.log(this.file);
/*
// Validate request
if (!req.body) {
res.status(400).send({
message: "Content can not be empty!",
});
}
// Create a Poste
const poste = new Poste({
titre: req.body.titre,
description: req.body.description,
// image_link: req.bodyimage_link,
nb_commentaires: req.body.nb_commentaires,
nb_likes: req.body.nb_likes,
nb_dislikes: req.body.nb_dislikes,
user_id: req.body.user_id,
date_cree: req.body.date_cree,
});
// Save Poste in the database
Poste.create(poste, (err, data) => {
if (err)
res.status(500).send({
message: err.message || "Some error occurred while creating the Poste.",
});
else res.send(data);
});
*/
};
这是前端看到的js总是我在控制台中有文件它收到答案但它没有定义
<template>
<div class="d-flex justify-content-center">
<form
@submit.prevent="submit"
enctype="multipart/form-data"
class="largeur80 my-5 shadow bordurePost bordureRond"
>
<div class="form-group">
<label class="text-primary" for="titre">Titre du post</label>
<input
type="text"
class="form-control"
name="titre"
placeholder="title..."
v-model.trim="$v.titre.$model"
/>
</div>
<div class="error" v-if="!$v.titre.required && submitStatus === 'ERROR'">
Field is required
</div>
<div class="form-group">
<label class="text-primary" for="description">Description</label>
<textarea
class="form-control"
name="description"
rows="3"
placeholder="Décrire le post..."
v-model.trim="$v.description.$model"
></textarea>
</div>
<div
class="error"
v-if="!$v.description.required && submitStatus === 'ERROR'"
>
Field is required
</div>
<div class="form-group">
<label class="text-primary" for="image_link"
>Ajouter une image ou multimedia</label
>
<input type="file" ref="file" class="file-input" @change="upload" />
</div>
<!--
<div
class="error"
v-if="!$v.image_link.required && submitStatus === 'ERROR'"
>
Field is required
</div>
-->
<div
class="form-group row d-flex align-item-center justify-content-center"
>
<div class="col-sm-10 ">
<button
type="submit"
class="bg-light btn btn-outline-primary"
:disabled="submitStatus === 'PENDING'"
>
Publier !
</button>
<p class="typo__p" v-if="submitStatus === 'OK'">
Thanks for your submission!
</p>
<p class="typo__p" v-if="submitStatus === 'ERROR'">
Please fill the form correctly.
</p>
<p class="typo__p" v-if="submitStatus === 'ERROR SERVEUR'">
erreur serveur:Le mot de passe ou l'email ne correponde pas OU
server HS !
</p>
<p class="typo__p" v-if="submitStatus === 'PENDING'">Sending...</p>
</div>
</div>
</form>
</div>
</template>
<script>
import { required, maxLength } from "vuelidate/lib/validators";
import axios from "axios";
export default {
name: "envoyer",
data() {
return {
file: "",
titre: "",
description: "",
image_link: null || "",
user_id: localStorage.getItem("userId") || null,
submitStatus: null,
};
},
validations: {
titre: { required, maxLength: maxLength(100) },
description: { required, maxLength: maxLength(500) },
image_link: {},
},
methods: {
upload() {
this.file = this.$refs.file.files[0];
console.log(this.file);
},
submit() {
const formData = new FormData();
formData.append("file", this.file);
console.log("requete ver serveur!");
this.$v.$touch();
if (this.$v.$invalid) {
this.submitStatus = "ERROR";
console.log("A echouer informations non complete!");
} else {
// do your submit logic here
console.log("En attente");
this.submitStatus = "PENDING";
axios
.post("http://localhost:3000/poste", this.file)
.then((response) => {
(this.submitStatus = "OK"), console.log(response);
console.log(this.file);
//this.$router.go("/post");
})
.catch(
(error) => (
(this.submitStatus = "ERROR SERVEUR"), console.log(error)
)
);
}
},
},
};
</script>
<style></style>
这是应用程序的照片
这是带有 multer 的中间件,它也在路由后调用和 app.use 中,我使用我在后面创建的静态图像文件的路径
// variable module npm multer
const multer = require("multer");
const MIME_TYPES = {
"image/jpg": "jpg",
"image/jpeg": "jpg",
"image/png": "png",
};
// logique pour les stockage telechargements de fichiers et modification d image avec multer
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, "images");
},
filename: (req, file, callback) => {
const name = file.originalname.split(" ").join("_");
const extension = MIME_TYPES[file.mimetype];
callback(null, name + Date.now() + "." + extension);
},
});
module.exports = multer({ storage: storage }).single("image");
如何恢复此图像文件并已使用我的配置将其接收到服务器???? 谢谢你回答我
解决方案
看来您没有在 axios 调用上发送formData
和发送。this.file
这是你在帖子中写的:
axios
.post("http://localhost:3000/poste", this.file)
这是要做的:
axios
.post("http://localhost:3000/poste", formData)
[更新]
您似乎也应该这样做formData.append('image', this.file)
,因为在后端您使用“图像”作为文件名:
module.exports = multer({ storage: storage }).single("image");
推荐阅读
- slack - 在 Konga 上设置警报/通知不起作用
- postgresql - 如何使用orderby和limit获取相关数据?
- python - python:运行台面模拟 - 如何保存每次运行的结果?
- html - div元素中的表格未在一行中对齐
- resource-scheduling - 跨多个唯一代理的有序任务的离线调度
- python - ValueError:未知层:自定义>CTCLayer。请确保将此对象传递给“custom_objects”参数
- html - 如何在没有一个或另一个的情况下在同一行中显示两个 JSX 元素?
- vulkan - 具有不同格式顶点的顶点缓冲区
- bootstrap-4 - 使容器更大,但不流畅
- flutter - 'List 类型的值