如何通过 Axios 将文件发送到 Laravel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42907747/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send a file via Axios to Laravel
提问by Hamed Kamrava
I need to post a File from client to server via Axios.
我需要通过 Axios 将文件从客户端发布到服务器。
Here is my Vuejs code :
这是我的 Vuejs 代码:
methods: {
'successUpload': function (file) {
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
axios.post('/Upload/File',file, config).then(function (response) {
console.log(response.data);
});
}
}
And here is my Laravel code for handling sent file :
这是我用于处理发送文件的 Laravel 代码:
public function uploadFile(Request $request)
{
if($request->hasFile('file'))
return "It's a File";
return "No! It's not a File";
}
But it always returns No It's not a File
.
但它总是返回No It's not a File
。
Any helps would be great appreciated.
任何帮助将不胜感激。
回答by whoacowboy
You have to create a FormData object and append the image file.
您必须创建一个 FormData 对象并附加图像文件。
methods: {
'successUpload': function (file) {
let data = new FormData();
data.append('file', document.getElementById('file').files[0]);
axios.post('/Upload/File',data).then(function (response) {
console.log(response.data);
});
}
}
An example is here.
一个例子是here。
Let me know if that works.
让我知道这是否有效。