使用表单数据上载Ajax文件Laravel 5.3 [英] Ajax File Upload With Form Data Laravel 5.3
问题描述
我想将一个 我的控制器是用户
的配置文件 image
上传到服务器,并且我被卡在ajax上所有我的表单数据都张贴到数据库
,包括图片名称 code>但是文件没有上传到服务器
我的视图是
$ pre> // form
{!! csrf_field()!!}
< div class =row>
< div class =col m12>
< div class =row>
< div class =input-field col m12 s12>
< input id =namename =nametype =textplaceholder =Full Nameclass =required validate>
< / div>
< div class =input-field col s12>
< input id =emailname =emailtype =emailplaceholder =Emailclass =required validate>
< / div>
< div class =input-field col s12>
< input id =phone_numbername =phone_numbertype =telplaceholder =Phone Numberclass =required validate>
< / div>
< div class =input-field col m6 s12>
< input id =addressname =address_city_villagetype =textplaceholder =Address City Village>
< / div>
< div class =input-field col m6 s12>
< input id =statename =address_statetype =textplaceholder =State>
< / div>
< div class =input-field col s12>
< input id =passwordname =passwordtype =passwordplaceholder =Passwordclass =required validate>
< / div>
< div class =input-field col s12>
< input id =confirmname =confirmtype =passwordplaceholder =Confirm Passwordclass =required validate>
< / div>
< div class =file-field input-field col s12>
< div class =btn teal lighten-1>
< span>图片< / span>
< input type =filename =image>
< / div>
< div class =file-path-wrapper>
< input class =file-path validatetype =text>
< / div>
< / div>
< / div>
< / div>
< / div>
< / div>
< / div>
< div class =modal-footer>
<按钮类型=submitclass =波浪效果波浪绿色btn蓝色>提交< /按钮>
< / div>
< / form>
$ b $ ajax
$(document).on(click,.agent-add,function(){
var agent_id = $( ();
$('form')。submit(function(event){
event.preventDefault();
$ .ajax
({
url:'{{url('/ agents')}}',
type:'POST',
data:{
_method: (POST),
name:$('input [name = name]')。val(),
email:$('input [name = email]')。val ),
的PHONE_NUMBER:$( '输入[名称= PHONE_NUMBER]')VAL(),
的address_city_village:$( '输入[名称= address_city_village]')VAL()。
address_state:$('input [name = address_state]')。val(),
image:$('input [name = image]')。val(),
password:$('input [name = password]')。val()
},
success:function(result )
{
location.reload();
},
错误:函数(数据)
{
console.log(data);
}
});
});
});
public function store(Request $ request)
{
if(User :: where('phone_number','=',Input :: get('phone_number')) - > ; exists()){
return $ this-> respondBadRequest('Phone Number Exists');
}
else
{
User :: create($ request-> all());
返回重定向('agents') - >与('Success','Agent Added');
if($ request-> hasFile('image')){
$ file = $ request-> file('image');
//你还需要保持文件的扩展名,以及
$名称= $文件 - > getClientOriginalName()$文件 - >。; getClientOriginalExtension();
//使用数组而不是对象
$ image ['filePath'] = $ name;
$ file-> move(public_path()。'/ uploads /',$ name);
$ b $ / code $ / pre
$ b $我猜我缺少一些在 ajax发布
的东西,但我无法弄清楚c> dd($ request-> all());
结果是
数组:9 [▼
_token=> heSkwHd8uSIotbqV1TxtAoG95frcRTATgeGL0aPM
name=> fwe
email=> sanjiarya2112@gmail.com
phone_number=> 4444422555
address_city_village=> sgf
address_state=> gfdgsdf
password=> ffffff
confirm=> ffffff
image=> UploadedFile {#208▼
-test:false
-originalName:Screenshot(8).png
-mimeType:image / png
-size:135920
-error:0
path:C:\wamp\tmp
filename:php47F2.tmp
basename:php47F2.tmp
pathname: C:\wamp\tmp\php47F2.tmp
扩展: TMP
的真实路径: C:\wamp\tmp\php47F2.tmp
ATIME :2017-01-24 06:14:40
m时间:2017-01-24 06:14:40
c时间:2017-01-24 06:14:40
inode:0
size:135920
perm:0100666
owner:0
group:0
type:file
可写:true
可读: true
executable:false
file:true
dir:false
link:false
linkTarget:C:\wamp\tmp\php47F2.tmp
$ b我检查了 C: \wamp\tmp\php47F2.tmp
enen那里我没有找到图像
期望获得非常需要的帮助
谢谢
解决方案 在上传文件时,尝试使用 ajax
中的 FormData
$ b
只要试试这个
$('form')。submit(function ){
event.preventDefault();
var formData = new FormData($(this)[0]);
$ .ajax({
url:'{{url('/ agents')}}',
type:'POST',
data:formData,
成功:函数(结果)
{
location.reload();
},
错误:函数(数据)
{
console.log (data);
}
});
});
或
<您可以尝试使用 jQuery
library
https://github.com/malsup/form
编辑
public function store(Request $ request)
{
if(User :: where('phone_number','=',Input :: get('phone_number')) - > exists()) {
return $ this-> respondBadRequest('Phone Number Exists');
}
else
{
$ user = User :: create($ request-> all());
if($ request-> hasFile('image')){
$ file = $ request-> file('image');
//你还需要保持文件的扩展名,以及
$名称= $文件 - > getClientOriginalName()$文件 - >。; getClientOriginalExtension();
//使用数组而不是对象
$ image ['filePath'] = $ name;
$ file-> move(public_path()。'/ uploads /',$ name);
$ user-> image = public_path()。'/ uploads /',$ name;
$ user-> save();
}
返回重定向('agents') - &(使用('Success','Agent Added');
}
}
i want to upload a profile image
of a user
to the server and i'm stuck at ajax upload of image
all my form data are posting to database
including the image name
but the file is not uploading to the server
my view is
//form
<form id="example-form" method="post" enctype="multipart/form-data">
{!! csrf_field() !!}
<div class="row">
<div class="col m12">
<div class="row">
<div class="input-field col m12 s12">
<input id="name" name="name" type="text" placeholder="Full Name" class="required validate">
</div>
<div class="input-field col s12">
<input id="email" name="email" type="email" placeholder="Email" class="required validate">
</div>
<div class="input-field col s12">
<input id="phone_number" name="phone_number" type="tel" placeholder="Phone Number" class="required validate">
</div>
<div class="input-field col m6 s12">
<input id="address" name="address_city_village" type="text" placeholder="Address City Village">
</div>
<div class="input-field col m6 s12">
<input id="state" name="address_state" type="text" placeholder="State">
</div>
<div class="input-field col s12">
<input id="password" name="password" type="password" placeholder="Password" class="required validate">
</div>
<div class="input-field col s12">
<input id="confirm" name="confirm" type="password" placeholder="Confirm Password" class="required validate">
</div>
<div class="file-field input-field col s12">
<div class="btn teal lighten-1">
<span>Image</span>
<input type="file" name="image">
</div>
<div class="file-path-wrapper">
<input class="file-path validate" type="text" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="waves-effect waves-green btn blue">Submit</button>
</div>
</form>
//ajax
$(document).on("click", ".agent-add", function () {
var agent_id = $(this).data('id');
$('form').submit(function(event) {
event.preventDefault();
$.ajax
({
url: '{{ url('/agents') }}',
type: 'POST',
data: {
"_method": 'POST',
"name": $('input[name=name]').val(),
"email": $('input[name=email]').val(),
"phone_number": $('input[name=phone_number]').val(),
"address_city_village": $('input[name=address_city_village]').val(),
"address_state": $('input[name=address_state]').val(),
"image": $('input[name=image]').val(),
"password": $('input[name=password]').val()
},
success: function(result)
{
location.reload();
},
error: function(data)
{
console.log(data);
}
});
});
});
my controller is
public function store(Request $request)
{
if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
return $this->respondBadRequest('Phone Number Exists');
}
else
{
User::create($request->all());
return redirect('agents')->with('Success', 'Agent Added');
if($request->hasFile('image')) {
$file = $request->file('image');
//you also need to keep file extension as well
$name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
//using array instead of object
$image['filePath'] = $name;
$file->move(public_path().'/uploads/', $name);
}
}
}
i guess i'm missing something in ajax posting
, but i couldn't figure it out
i dd($request->all());
the result is
array:9 [▼
"_token" => "heSkwHd8uSIotbqV1TxtAoG95frcRTATgeGL0aPM"
"name" => "fwe"
"email" => "sanjiarya2112@gmail.com"
"phone_number" => "4444422555"
"address_city_village" => "sgf"
"address_state" => "gfdgsdf"
"password" => "ffffff"
"confirm" => "ffffff"
"image" => UploadedFile {#208 ▼
-test: false
-originalName: "Screenshot (8).png"
-mimeType: "image/png"
-size: 135920
-error: 0
path: "C:\wamp\tmp"
filename: "php47F2.tmp"
basename: "php47F2.tmp"
pathname: "C:\wamp\tmp\php47F2.tmp"
extension: "tmp"
realPath: "C:\wamp\tmp\php47F2.tmp"
aTime: 2017-01-24 06:14:40
mTime: 2017-01-24 06:14:40
cTime: 2017-01-24 06:14:40
inode: 0
size: 135920
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\wamp\tmp\php47F2.tmp"
}
]
i checked the C:\wamp\tmp\php47F2.tmp
enen there i din't find the image
looking forward for much needed help
thank you
解决方案 Try using the FormData
in ajax
while you upload a file.
Just try this
$('form').submit(function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '{{ url('/agents') }}',
type: 'POST',
data: formData,
success: function(result)
{
location.reload();
},
error: function(data)
{
console.log(data);
}
});
});
OR
You can try with this jQuery
library
EDIT
public function store(Request $request)
{
if (User::where('phone_number', '=', Input::get('phone_number'))->exists()) {
return $this->respondBadRequest('Phone Number Exists');
}
else
{
$user=User::create($request->all());
if($request->hasFile('image')) {
$file = $request->file('image');
//you also need to keep file extension as well
$name = $file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
//using array instead of object
$image['filePath'] = $name;
$file->move(public_path().'/uploads/', $name);
$user->image= public_path().'/uploads/', $name;
$user->save();
}
return redirect('agents')->with('Success', 'Agent Added');
}
}
这篇关于使用表单数据上载Ajax文件Laravel 5.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文