我正在为一个个人项目制作一个管理面板,作为研究laravel框架的一种方式,到目前为止,我很喜欢它!
我遇到一个问题,我不知道如何将上传的图像存储到我的应用程序中(尽管不太安全,但我想使用公用文件夹而不是其他存储),我的文件夹名为“ uploads”公开的。
这是我的AJAX POST呼叫:
$('.form_store_button').click(function(){
var linked_entry = $(this).attr("data-link");
var form = $(this).closest('form');
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
});
switch(linked_entry) {
case "sliders":
console.log('new slider button clicked');
var formData = new FormData();
formData.append('title', form.closest($("input[name='title']").val()));
formData.append('body', form.closest($("textarea[name='body']").val()));
formData.append('image', form.closest($("input[name='image']").prop('files')[0]));
formData.append('isVisible', form.closest($("input[name='isVisible']").is(':checked') ? 1 : 0));
$.ajax({
async: true,
url: '/sliders',
type: 'POST',
data: formData,
dataType: 'JSON',
processData: false,
contentType: false,
success: function (data) {
$('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(){
$('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
});
}
});
break;
default:
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
这是我尝试存储图像的控制器(但最终会失败)。
public function store(StoreSlider $request)
{
$slider = new Slider();
$slider->title = $request->title;
$slider->body = $request->body;
$slider->image = $request->file('image');
$slider->isVisible = $request->isVisible;
$slider->save();
return response()->json($slider);
}
答案 0 :(得分:0)
要遵循的步骤,
要存储图像,您需要具有以下数据,
public function store(StoreSlider $request) { $uploadFile = $request->file('image'); //generate random filename and append original extension (eg: asddasada.jpg, asddasada.png) $filename = str_random(6).'.'.$uploadFile->extension(); // storing path (Change it to your desired path in public folder) $path = 'img/uploads'; // Move file to public filder $uploadFile->storeAs('../../public/'.$path, $filename); $slider = new Slider(); $slider->title = $request->title; $slider->body = $request->body; $slider->image = $path.'/'.$filename; // So that you can access image by url($slider->image); $slider->isVisible = $request->isVisible; $slider->save(); return response()->json($slider); }