如何在 Vue.Js 中使用 $http.post 发送文件 [英] How to send an file with $http.post in Vue.Js
本文介绍了如何在 Vue.Js 中使用 $http.post 发送文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 vue.js 发送文件?
How can I send a file with vue.js?
以下代码对我不起作用:
The following code is not working for me:
<span title="Upload" class="badge badge-info">
<input type="file" id="file" name="file" @change="uploadData" class="archive" > <i id="iarchive" class="fa fa-upload"></i>
</span>
当我制作 console.log(this.request.file)
我得到 FILE [object File]
.
When I make console.log(this.request.file)
I get FILE [object File]
.
这是 .js:
uploadData: function(e) {
var files = e.target.files[0];
this.request.action = 'upload';
this.request.file = files;
console.log("FILE "+this.request.file);
this.$http.post('data/getData.php', {
data: this.request,
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(function(response) {
console.log("RESPONSE: "+response.body);
}, function(response) {
alert("error");
});
return false;
}
但在 PHP 中,我无法获取文件,响应为:{} No properties
.
But in PHP, I can't get the file, the response is :{} No properties
.
PHP 代码:
$request = json_decode(file_get_contents('php://input'));
$req = $request->data;
echo json_encode($req->file)
推荐答案
向输入添加 ref 属性:
Add ref attribute to input:
<input ref="file-input" .../>
在控制器中你应该写动作:
In controller you should write action:
uploadFile: function () {
// try to log $refs object for deep understanding
let fileToUpload = this.$refs.fileInput.files[0];
let formData = new FormData();
formData.append('fileToUpload', fileToUpload);
this.$http.post ( 'data/getData.php', formData ).then(function () {
// success actions
});
}
在 php 端点中,您上传的文件将在表单请求对象中.
In php endpoint your uploaded files will be in form request object.
这篇关于如何在 Vue.Js 中使用 $http.post 发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文