javascript - 用vue上传文件,nodejs接收

标签 javascript node.js vue.js

我正在尝试使用 vuejs 将文件上传到服务器,实际上我不希望表单处理文件并上传它,我阻止提交并自己处理一些逻辑,所以一开始我想做一些简单的事情,只要检查它是否是 pdf,如果一切正常,它应该指向为 NodeJS 服务器定义的本地主机中的/upload

<template>
  <div id="app">
    <form>
      <h2>Select a file</h2>
      <input id="inputVal" type="file" @change="onFileChange">
      <button @click.prevent="sendFile()">Send</button>
    </form>
  </div>
</template>

<!-- Javascript -->
<script>
  export default {
    name: 'app',
    data() {
      return {
        file: ''
      }
    },
    methods: {
      onFileChange(e) {
        var files = e.target.files || e.dataTransfer.files;
        if (!files.length) {
          return;
        }
        var ext = files[0].name.split('.').pop();
        if(ext === 'pdf') {
          this.createFile(files[0]);
        }
        else {
          this.file = '';
          this.clearFileInput(document.getElementById('inputVal'));
        }
      },
      createFile(file) {
        this.file = file;
      },
      clearFileInput(ctrl) {
        try {
          ctrl.value = null;
        } catch(ex) { }
        if (ctrl.value) {
          ctrl.parentNode.replaceChild(ctrl.cloneNode(true), ctrl);
        }
      },
      sendFile() {
        var vm = this;
        if(this.file !== '') {
         this.$http.post('http://localhost:3000/upload',{params: vm.file, headers: {'Content-Type': 'multipart/form-data'}})
        .then(response => {
          // JSON responses are automatically parsed.
          //
        }, error => {
          //this.errors.push(e)
        });
      }
    }
  }
}
</script>

在我的服务器端,我收到未定义的消息,我真的不知道为什么,我只是想看看我是否真的在服务器中有任何文件,如果是,我想将它保存在服务器端,任何帮助那个?

我刚刚在/upload 端点上做了这个:

router.post('/upload',function(req,res) {
  console.log(res.body);
})

最佳答案

你会得到Files来自输入的对象不是实际文件而是对文件的特殊引用,您需要使用 FileReaderFormData要获取实际文件并发送它,请尝试这样的操作

var data = new FormData();
var pdf = e.target.files[0];
data.append('file',pdf)
this.$http.post('http://localhost:3000/upload',{params: data}, headers: {'Content-Type': 'multipart/form-data'}})

关于javascript - 用vue上传文件,nodejs接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46223495/

相关文章:

javascript - React-admin 的 dataProvider 是否应该对数据应用格式?

node.js - Grunt 失败构建 "Arguments to path.join must be strings"错误

javascript - Hapi - 用 HTML 回复

vue.js - 在 Vue 2.0 中切换 CSS 类

javascript - 页面刷新时导航到另一个路由 vuejs

javascript - [Vue 警告] : Error in render function: "TypeError: Cannot read property ' first_name' of null"

javascript - 如何异步运行斐波那契函数?

javascript - Node js 如何使用 "node_modules"库而不是 "src =<cdn>"

javascript - 绑定(bind)两个输入,以便即使其中之一被用户更改,它们也会显示相同的文本

javascript - 使用 NVM 的 Vim 的 Tern JS