[英]Upload image via ajax in Laravel 5
I have a little problem with code. 我的代码有一点问题。
I can't receive input image in my controller. 我无法在控制器中接收输入图像。 Then I use print_r($input);
然后我使用print_r($input);
I receive empty array. 我收到空数组。
My js code: 我的js代码:
$(document).on('click', '#photo-upload #upload-button', function(e) {
e.preventDefault();
$.ajax({
url: "/photo/upload/",
data: new FormData($("#photo-upload")[0]),
dataType:'json',
type:'GET',
processData: false,
contentType: false,
success: function ( data ) {
alert("succes!");
},
error: function ( data ) {
alert("error");
}
});
});
my form: 我的表格:
<div class="full-cell">
<span>Название</span>
</div>
<div class="full-cell">
<input type="text" name="name" class="input-full" id="name">
</div>
<div class="full-cell">
<span>Описание</span>
</div>
<div class="full-cell">
<textarea name="description" id="description" cols="30" rows="3"></textarea>
</div>
<div class="full-cell">
<span>Загрузить в альбом:</span>
<select name="album" id="album">
@foreach ($albums as $album)
@include('partials.select._album_names')
@endforeach
</select>
</div>
<div class="file">
<input type="file" name="image" id="fileInput"/>
</div>
<div class="window-footer">
<button type="button" class="auth-button btn-sec" id="upload-cancel">Отмена</button>
<button type="submit" class="auth-button btn-advanced" id="upload-button" hidden="">Загрузить</button>
</div>
</form>
My controller: 我的控制器:
public function store(Request $request) {
$user = Auth::user(); //Данные учетной записи
$input = Input::all();
$image = Input::file('image'); //Записываем картинку в переменную
print_r($input);
$filename = $user->username . '.' . $image->getClientOriginalExtension(); //Создаем новое имя файла
$date = date('Y-m-d'); //Получаем дату
$path = "user_data/photos/$date/"; //Создаем путь до оригинала
$thumbnail_path = "user_data/photos/$date/thumbnail/"; //Создаем путь до миниатюры
File::makeDirectory("$path", 0775, true, true); //Директория для фото
File::makeDirectory("$thumbnail_path", 0775, true, true); //Директория для миниатюры
$image->move($path, $filename); //Сохраняем картинку на сервер
$photo = "$path" . $filename; //Адрес фото
$thumbnail = "$thumbnail_path" . $filename; //Адрес миниатюры
File::copy($photo, $thumbnail); //копируюм фото в миниатюры
$image = Image::make($thumbnail)->fit(153,90)->save();
$new_photo = new Photo;
$new_photo->owner_id = $user->id;
$new_photo->name = $input['name'];
$new_photo->description = $input['description'];
$new_photo->photo = "/$photo";
$new_photo->thumbnail = "/$thumbnail";
$new_photo->album_id = $input['album'];
$new_photo->save();
}
Ajax Code Ajax代码
var formData = new FormData();
formData.append("file",$('#fileForm16')[0].files[0]);
formData.append("password",$("#textPassword").val());
$.ajax({
url: "{{url("api/uploadfiles")}}",
data: formData,
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
success: function (response) {
console.log(response);
}
});
Laravel Code Laravel代码
if (($request->hasFile('file'))) {
$destinationPath = 'uploads/files'; // upload path
$extension = $request->file('file')->getClientOriginalExtension(); // getting image extension
$tempName = $request->file("file")->getClientOriginalName();
$fileName = uniqid("MW") . '.' . $extension; // renameing image
$request->file('file')->move($destinationPath, $fileName); // uploading file to given path
// sending back with message
$imagepath = $destinationPath.'/'.$fileName;
}
i found a solution of this problem! 我找到了这个问题的解决方案! i need use diferent even on my upload button. 我甚至需要在上传按钮上使用不同的内容。 i did use this event: $(document).on('click', '#photo-upload #upload-button', function(e) - and this not work! now i use this event: $(document).on('submit', '#photo-upload', function(e) and code work fine!!! thx for all. Hope this will help anybody) 我确实使用了此事件:$(document).on('click','#photo-upload#upload-button',function(e)-这不起作用!现在我使用此事件:$(document).on ('submit','#photo-upload',function(e)和代码可以正常工作!谢谢所有人。希望这对任何人都有帮助)
尝试改用Request。
$request->all()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.