【问题标题】:How to handle images in Vue Js form如何处理 Vue Js 表单中的图像
【发布时间】:2021-01-21 22:36:58
【问题描述】:

我在 Vue 中有一个用于上传博客文章的表单,其中包含标题、正文、描述、sn-p 和照片区域。都是必需的。我在 Express 中设置了一个 API 来处理这个问题,我在 Postman 中对其进行了测试,它可以工作,但我不知道如何从浏览器将文件发送到数据库。 我不断收到 500 错误,我将数据打印到控制台并且照片字段为空,所以我确定这是问题所在,但我无法弄清楚。

这是我在前端的表单:

<template>
  <div class="container">
    <div id="nav">
      <adminnav/>
    </div>
    <div id="create">
      <h1>Create new post</h1>
    </div>
    <div id="post">
      <body>
        <form>
          <label for="title">Title: </label>
          <textarea v-model=formdata.title rows="5" cols="60" name="title"
            placeholder="Enter text">
          </textarea>
          <br/>
          <label for="body">Body: </label>
          <textarea v-model=formdata.body rows="5" cols="60" name="body"
            placeholder="Enter text">
          </textarea>
          <br/>
          <label for="description">Description: </label>
          <textarea v-model=formdata.description rows="5" cols="60" name="description"
            placeholder="Enter text">
          </textarea>
          <br/>
          <label for="snippet">Snippet: </label>
          <textarea v-model=formdata.snippet rows="5" cols="60" name="snippet"
            placeholder="Enter text">
          </textarea>
          <br/>
          <label for="file">Upload photo: </label>
          <input
            class="form-control-file"
            type="file"
            accept="image/*"
            v-bind="formdata.photo"
          />
          <br/>
          <input id="submit" type="submit" value="submit" @click.prevent="createPost()"/>
        </form>
      </body>
    </div>
  </div>
</template>

<script>
import adminnav from '../components/adminnav.vue';
import PostService from '../service/PostService';

export default {
  name: 'createStory',
  components: {
    adminnav,
  },
  data() {
    return {
      formdata: {
        title: '',
        body: '',
        description: '',
        snippet: '',
        photo: null,
      },
    };
  },
  methods: {
    createPost() {
      console.log(this.formdata);
      /* eslint prefer-destructuring: 0 */
      const formdata = this.formdata;
      PostService.createPost(formdata)
        .then(() => {
          console.log('success');
        });
    },
  },
};
</script>

这是 POST 请求。

router.post("/add-story", upload.single('photo'), async(req, res) => {
  try{
    let post = new Post();
    post.title = req.body.title;
    post.description = req.body.description;
    post.photo = req.file.location;
    post.body = req.body.body;
    post.snippet = req.body.snippet;

    await post.save();
    
    res.json({
      status: true,
      message: "Successfully saved."
    });
    
  } catch(err) {
    res.status(500).json({
      success: false,
      message: err.message
    });
  }
});

【问题讨论】:

    标签: javascript rest express vue.js


    【解决方案1】:

    让我们监视文件&lt;input&gt;change 事件。这样可以确保每次用户的上传行为都会触发updatePhoto方法并将文件数据存储在this.photo中。

    <input type="file" accept="image/*" class="form-control-file"
        @change="updatePhoto($event.target.name, $event.target.files)"
    >
    

    收集所有数据并发送请求的代码

    // Other parts of your vue component
    data () {
        return {
            title: '',
            body: '',
            description: '',
            snippet: '',
            photo: {} // To store file data
        };
    },
    methods: {
        updatePhoto (files) {
            if (!files.length) return;
    
            // Store the file data
            this.photo = {
                name: files[0].name,
                data: files[0]
            };
        },
        createPost() {
            let formData = new FormData();
    
            formData.append('title', this.title);
            formData.append('body', this.body);
            formData.append('description', this.description);
            formData.append('snippet', this.snippet);
            formData.append('photo', this.photo.data, this.photo.name);
    
            PostService.createPost(formdata)
            .then(() => {
                console.log('success');
            });
        }
    }
    // Other parts of your vue component
    

    显然我跳过了很多东西,比如我认为与这个问题无关的整个 vue 组件结构,以及一些必要的检查以确保在启动请求之前有可用的文件数据等等。这是一个关于你如何的想法可以获取文件数据所以希望这个答案能启发你。

    【讨论】:

    • 这行得通。我不得不删除 '$event.target.name' 并且其他地方的名字都出现了,因为它给了我一个奇怪的错误。无论如何,文件的名称都不是必需的,所以我没有深入研究它。欣赏它!
    猜你喜欢
    • 2019-02-20
    • 2017-12-11
    • 1970-01-01
    • 2022-01-03
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 2019-09-28
    • 1970-01-01
    相关资源
    最近更新 更多