我正在尝试使用ajax和laravel将图像上传到数据库和文件夹,但是我收到的错误如call to a member function getclientoriginalextension on string
,而且我的控制器图像路径中的值只是没有来。
我的观点:
<form role="form" name="campaignForm" id="campaignForm" action="" method="post" enctype="multipart/form-data">
<input type="text" name="project_name" autocomplete="off" id="project_name" placeholder="Company name" class="form-control">
<input type="text" name="website_url" id="website_url" autocomplete="off" placeholder="http://www.yourdomain.com" class="form-control">
<input type="file" name="image" id="image" autocomplete="off" placeholder="" class="form-control">
<input type="text" name="location" id="location" autocomplete="off" placeholder="Enter the location you want to target" class="form-control">
<input type="text" name="group" id="group" autocomplete="off" placeholder="Group (optional)" class="form-control">
<button type="submit" id="btn-save" value="add" class="btn actionBtn btn-primary">
</form>
我的ajax:
$("#btn-save").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
e.preventDefault();
var formData = {
project_name: $('#project_name').val(),
website_url: $('#website_url').val(),
location: $('#location').val(),
group: $('#group').val(),
image : $('#image').val(),
}
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
});
控制器:
public function campaign(Request $request){
$task = new projects();
$task->project_name = trim($request->project_name);
$task->website_url = trim($request->website_url);
$task->location = trim($request->location);
$task->group = trim($request->group);
$file = trim($request->image);
if ($request->hasFile($file)) {
$destinationPath = 'images'; // upload path
$extension = $file->getClientOriginalExtension(); // getting image extension
$fileName = rand(11111,99999).'.'.$extension; // renameing image
$file->move($destinationPath, $fileName);
$task->image = $fileName;
}
dd($task);
}
任何帮助都将不胜感激。谢谢。
答案 0 :(得分:1)
看起来Laravel没有收到上传的图片。 $request->image
应该是UploadedFile
类的实例,但在您的情况下,它只是"C:\fakepath\custom-image.jpg"
尊重this answer,试试这个:
$("#btn-save").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
e.preventDefault();
var form = document.forms.namedItem("campaignForm"); // high importance!, here you need change "yourformname" with the name of your form
var formData = new FormData(form); // high importance!
$.ajax({
type: type,
url: my_url,
dataType: "json", // or html if you want...
contentType: false, // high importance!
data: formData, // high importance!
processData: false, // high importance!
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
});