gpt4 book ai didi

javascript - Laravel 5 中通过 ajax 上传图像

转载 作者:行者123 更新时间:2023-11-28 10:45:37 25 4
gpt4 key购买 nike

我的代码有一点问题。

我无法在 Controller 中接收输入图像。然后我使用 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>

我的 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 代码

  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;


}

关于javascript - Laravel 5 中通过 ajax 上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43711729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com