[英]Upload image via ajax in Laravel 5
我的代碼有一點問題。
我無法在控制器中接收輸入圖像。 然后我使用print_r($input);
我收到空數組。
我的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");
}
});
});
我的表格:
<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>
我的控制器:
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代碼
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代碼
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;
}
我找到了這個問題的解決方案! 我甚至需要在上傳按鈕上使用不同的內容。 我確實使用了此事件:$(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.