[英]How to send files in Vuejs?
I have two scripts 我有两个脚本
first in Vue component: Vue组件中的第一个:
var data = {
cover: myResult[0], // first file
file: myResult[1], // second file
title: self.title, // first string
desc: self.desc // second string
};
self.$http.post('tracks.post', data)
.then(res =>{
console.log(data); // 1*
console.log(res); // 2*
})
And php script on server: 和服务器上的php脚本:
dd(file_get_contents('php://input')); // 3*
dd($_FILES); // 4*
dd() - just a function to see what in parametr dd()-只是一个函数,可查看参数中的内容
1* - all is good, all strings and file exists: 1 *-一切都很好,所有字符串和文件都存在:
Object {cover: File, file: File, title: "ada", desc: "asdasd"}
2* - not all is good (explanation next) 2 *-并非都很好(接下来说明)
3* - there shows only strings, but files are disappeared: 3 *-仅显示字符串,但文件消失了:
string(52) "{"cover":{},"file":{},"title":"ada","desc":"asdasd"}"↵
4* - in $_FILES also not exists files: 4 *-$ _FILES中的文件也不存在:
array(0) {↵}↵
So, How I should to send files in vuejs? 那么,我应该如何在vuejs中发送文件?
I have no idea how to send files in VueJS. 我不知道如何在VueJS中发送文件。 What I do know is that I ran into a similar issue with angularjs a year ago.
我所知道的是,一年前我也遇到了与angularjs类似的问题。 My solution was to use javascript FormObject() for sending data to the server instead of just using Object().
我的解决方案是使用javascript FormObject()将数据发送到服务器,而不仅仅是使用Object()。 I also had to write a custom directive which looked like this
我还必须编写一个看起来像这样的自定义指令
<input data-file id="id_image" name="image" ng-model="museumMap" type="file">
myApp.directive('file', function() {
return {
require:"ngModel",
restrict: 'A',
link: function($scope, el, attrs, ngModel){
el.bind('change', function(event){
var files = event.target.files;
var file = files[0];
ngModel.$setViewValue(file);
$scope.$apply();
});
}
};
});
I know this doesnt directly answer your question, but hopefully it gives you a starting point. 我知道这并不能直接回答您的问题,但希望它能为您提供一个起点。 Id try using FormObject() first.
请先尝试使用FormObject()。
After few hours of tests, I founded right way to post files with strings: 经过几个小时的测试,我建立了正确的方法来发布带有字符串的文件:
let data = new FormData();
data.append('token', self.$auth.getToken());
data.append('file', file);
data.append('cover', cover);
data.append('title', self.title);
data.append('desc', self.desc);
And then just send the data as usuall. 然后像往常一样发送数据。 Hope it helps someone in future.
希望以后能对某人有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.