我有桌面用户:
我想使用ajax jquery在我的数据库中插入图像。
但是在给定的数据库级别,它不会在图像中插入数据。
我尝试使用此代码但不起作用。
控制器:
public function addUser(Request $request){
$user = new User();
$user->lastName = $request->lastName;
$user->firstName = $request->firstName;
$user->email = $request->email;
$user->login = $request->login;
$user->password = bcrypt($request->password);
if($request->has('image') ) {
$file_local = $request->file('image');
$extension = $request->file('image')->getClientOriginalExtension();
if($extension == 'jpg' || $extension == 'png' || $extension == 'jpeg'){
$name=$request->file('image')->getClientOriginalName();
$path = $file_local->storeAS('public/',$name);
$user->image = $name;
}
}
$user->save();
return response()->json($user);
}
查看:
<form enctype="multipart/form-data">
<div class="form-group">
<input type="text" id="lastName" class="form-control" placeholder="last Name" required />
</div>
<div class="form-group">
<input type="text" id="firstName" class="form-control" placeholder="name" required />
</div>
<div class="form-group">
<input type="email" id="email" class="form-control" placeholder="Email" required/>
</div>
<div class="form-group">
<input type="text" id="login" class="form-control" placeholder="Login" required/>
</div>
<div class="form-group">
<input type="password" id="password" class="form-control" placeholder="password" required/>
</div>
<div class="form-group">
<input type="file" id="image" class="form-control" required />
</div>
</form>
AJAX :
$(document).on('click', "#creer_utilisateur", function() {
var lastName= $('#lastName').val();
var firstName = $('#firstName').val();
var email = $('#email').val();
var login = $('#login').val();
var password = $('#password').val();
var image = $('#image').val();
success: function(data) {
$.ajax({
url: "{{action('UserController@addUser')}}",
method: 'POST',
data: {
lastName: lastName,
firstName: firstName,
email: email,
login: login,
password: password,
image: image
},
success: function(data) {
alert('success');
},
error: function(){
alert('failed');
}
});
}
});
});
答案 0 :(得分:0)
您实际上是在保存图片的名称:
$name=$request->file('image')->getClientOriginalName();
...
$user->image = $name;
你说:
&#34;但在给定的数据库级别,它不会在图像中插入数据。&#34;
列的类型是:
image (text)
所以,我想你不想存储这个名字,对吧?
答案 1 :(得分:0)
当您使用ajax上传文件时,您需要使用File属性创建表单。然后用它附加其他值。
这样的事情:
var formData = new FormData();
if ($('#images')[0].files.length > 0) {
for (var i = 0; i < $('#images')[0].files.length; i++)
formData.append('file[]', $('#images')[0].files[i]);
}
formData.append('lastName', $('#lastName').val());
当您使用ajax传递文件时,请确保缓存为false。
$.ajax({
type: 'POST',
dataType: "JSON",
url: jQuery('form').attr('action'),
xhr: function() {
myXhr = $.ajaxSettings.xhr();
return myXhr;
},
cache: false,
contentType: false,
processData: false
data: formData,
success: function(data) {
// Success
},
error: function(error) {
// error
},
});
祝你好运