2017-09-14 17 views
0

我想用vuejs上傳一個文件到服務器,實際上我不想用表單來處理文件並上傳它,我阻止自己提交和處理一些邏輯,所以在開始我想要做一些簡單的只是檢查它是否是一個PDF格式,如果一切正常,應該指向我的服務器端進行的NodeJS服務器用vue上傳文件並接收它nodejs

<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> 

定義在本地主機/上傳我收到未定義,我不知道爲什麼,我只想看看我是否真的在服務器上有任何文件,如果是的話,我想將它保存在服務器端,任何幫助?

我只是做這在/上傳端點:

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

不應該是req.body,因爲它是請求中沒有響應的對象。 req = request,res = response。 – Adriani6

+0

,但我的params對象總是空{} –

+0

{params:{file:{}}, header:{'Content-Type':'multipart/form-data'}} –

回答

0

你會得到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'}})