使用Laravel中的Ajax保存路径图像


Save path image with Ajax in Laravel

我可以保存表单中的所有数据varchar/text元素,但不能保存路径图像。

我的代码出了什么问题?

让我们看看我的create.blade.php我可以保存var deadline的值,但我不能保存var path:的值

Form::open(array('url' => 'imagesLoker', 'files' => true))
    <form class="form-horizontal">
    <div class="box-body">
        <div class="form-group">
            {!!Form::label('Deadline Lowongan : ')!!}
            {!!Form::date('deadline',null,['id'=>'deadline','class'=>'form-control','placeholder'=>'Deadline Lowongan'])!!}
        </div>
        <div class="form-group">
            {!!Form::label('Image Lowongan : ')!!}
            {!!Form::file('path') !!}
        </div>
    </div><!-- /.box-body -->
</form>
{!!Form::close()!!}

这是我的控制器:

public function store(Request $request)
    {
        Lowongan::create($request->all());
        return "data all";
    }

这是我用Ajax创建的数据:

$("#createLoker").click(function(){
    var datas = $('form').serializeArray();
    var route = "http://localhost:8000/lowongan";
    var token = $("#token").val();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.post(route,{
        deadline: $("#deadline").val(),
        path: $("#path").val()
    }).done(function(result){
        console.log(result);
    });
});

我不知道这对在我的Modal中设置解析数据是否重要,但我只是把这段代码放在了我的Modal:中

class Lowongan extends Model
{
    protected $table = 'Lowongan';
    protected $fillable = ['path','deadline'];
    public function setPathAttribute($path){
        $this->attributes['path']  = Carbon::now()->second.$path->getClientOriginalName();
        $name = Carbon::now()->second.$path->getClientOriginalName();
        'Storage::disk('local')->put($name, 'File::get($path));
    }
}

最后我设置了保存图像的目录。这是config/filesystem:中的设置

'disks' => [
        'local' => [
            'driver' => 'local',
            'root'   => public_path('imagesLoker'),
        ],

我可以保存数据截止日期,但不适用于图像:(..如果有任何关于如何保存图像路径的想法,我会很高兴知道的。

在您的表单中,您必须允许类似laravel的文件上传选项。

Form::open(array('url' => 'foo/bar', 'files' => true))

检查laravel文档的文件上传部分

希望能有所帮助。。

请按照以下步骤

在视图中

{!!Form::file('path') !!}更改为{!!Form::file('file') !!}

在控制器中

请注意,我已将上传路径设置为root/public/uploads/文件夹

public function store(Request $request)
    {
        $file = Input::file('file');
        $path = '/uploads/';
        $newFileName = Carbon::now()->second.$file->getClientOriginalName(). '.' . $file->getClientOriginalExtension();
        // Move the uploaded file
        $upSuccess = $file->move(public_path() . $path, $newFileName);
        $result = file_exists(public_path() . $path . $newFileName);
        $fileData =[
            'fileType' => $file->getClientOriginalExtension(),
            'filePath' => substr($path, 1) . $newFileName
        ];
        Input::merge(array('path' => $fileData["filePath"]));
        Lowongan::create($request->all());
        return "data all";
    }