php Laravel 5 Ajax 文件/图片上传
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32367132/
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
Laravel 5 Ajax File/Image Upload
提问by Jishad P
I have an issue in my laravel ajax application,
我的 Laravel ajax 应用程序有问题,
I cant upload images/files through ajax POST.
我无法通过 ajax POST 上传图像/文件。
here is my code.
这是我的代码。
Ajax..
阿贾克斯..
/*Add new catagory Event*/
$(".addbtn").click(function(){
$.ajax({
url:'add-catagory',
data:{
logo:new FormData($("#upload_form")[0]),
},
dataType:'json',
async:false,
type:'post',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
/*Add new catagory Event*/
Blade template ...
刀片模板...
<form enctype="multipart/form-data" id="upload_form" role="form" method="POST" action="" >
<div class="form-group">
<label for="catagry_name">Name</label>
<input type="hidden" name="_token" value="{{ csrf_token()}}">
<input type="text" class="form-control" id="catagry_name" placeholder="Name">
<p class="invalid">Enter Catagory Name.</p>
</div>
<div class="form-group">
<label for="catagry_name">Logo</label>
<input type="file" class="form-control" id="catagry_logo">
<p class="invalid">Enter Catagory Logo.</p>
</div>
</form>
</div>
<div class="modelFootr">
<button type="button" class="addbtn">Add</button>
<button type="button" class="cnclbtn">Reset</button>
</div>
</div>
Controller ..
控制器 ..
public function catadd(){
if (Input::hasFile('logo'))
{
return "file present";
}
else{
return "file not present";
}
}
Route ..
路线 ..
Route::post('add-catagory',['as'=>'catagory_add','uses'=>'MastersController@catadd']);
What is the error in my code ???
我的代码有什么错误???
I cant get the file information in laravel controller..
我无法在 Laravel 控制器中获取文件信息..
How can i solve this issue...?
我该如何解决这个问题...?
回答by Iamzozo
Two things to change:
改变两件事:
Change your js file from:
从以下位置更改您的 js 文件:
data:{
logo:new FormData($("#upload_form")[0]),
},
To:
到:
data:new FormData($("#upload_form")[0]),
Because you would like to send the whole form.
因为您想发送整个表格。
In your html:
在你的 html 中:
Add a name to your file input field
将名称添加到您的文件输入字段
<input type="file" class="form-control" id="catagry_logo">
To:
到:
<input type="file" name="logo" class="form-control" id="catagry_logo">
回答by rotring05
it doesn't work for me because of dataType:'json'
. If anyone gets error just remove dataType:'json'
.
它对我不起作用,因为dataType:'json'
. 如果有人出错,只需删除dataType:'json'
.
回答by marko
Check in your controller what you get when you post:
在您的控制器中检查您在发布时获得的信息:
echo dd(Input::all());
Check files object in php. This in PHP:
检查php中的文件对象。这在 PHP 中:
$_FILES
Request::file("logo");
Yeah, you're not really posting any data? Is the form really posting?
是的,你不是真的发布任何数据?表格真的发布了吗?