【问题标题】:how to make my controllers post to process files with multer npm in frontend vus js and backend nodejs I don't happen recover files in backend?如何让我的控制器发布以在前端 vue js 和后端 nodejs 中使用 multer npm 处理文件我不会在后端恢复文件?
【发布时间】:2020-12-25 03:16:25
【问题描述】:

这里是后端,它总是告诉我未定义来查找文件

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");

如何恢复此图像文件并已使用我的配置将其接收到服务器????谢谢你回答我

【问题讨论】:

    标签: javascript node.js vue.js multer


    【解决方案1】:

    您似乎没有发送 formData 而是在 axios 调用中发送了 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");
    

    【讨论】:

    • 这里是添加formdata后顶部的图片但不是商品我不知道是什么问题??
    • 我没有看到任何图片,也许图片没有在 cmets 中显示?
    • 好的,它在帖子中,我现在看到了。我认为这是后端的问题。不幸的是,我不认识 Multer + 我不是 NodeJs 开发人员。但我的猜测是,multer 中预期的字段名称不是好名称?
    • 这里我现在在帖子中添加了它
    • 我想我知道发生了什么,所以基本上从我在这里读到的code.tutsplus.com/tutorials/…,你做了 multer( ... )..single("image") 但这不是你所说的在 formData 中的文件,您使用 formData.append('file', this.file) 而不是 formData.append('image', this.file)。你明白我的意思吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多