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);
})
不應該是req.body,因爲它是請求中沒有響應的對象。 req = request,res = response。 – Adriani6
,但我的params對象總是空{} –
{params:{file:{}}, header:{'Content-Type':'multipart/form-data'}} –