Laravel 4 图片上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22768579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:17:29  来源:igfitidea点击:

Laravel 4 image upload

phpjqueryfile-uploadlaravellaravel-4

提问by Kiwi

Hi, I'm trying to make an image upload via laravel, everything is working but now I want to change the upload to an jquery upload instead but then I get an 500 internal server error

嗨,我正在尝试通过 laravel 上传图片,一切正常,但现在我想将上传更改为 jquery 上传,但随后我得到了一个 500 internal server error

so when I handle things with Jquery it fails. Anyone knows what the problem might be? html:

所以当我用 Jquery 处理事情时它失败了。任何人都知道问题可能是什么?html:

{{ Form::open(array('url' => '../public/posts/add', 'class'=>'form-horizontal', 'role' => 'form', 'id' => 'addPin', 'files' => true)) }}

            <div id="validation-errors" class="alert alert-danger" hidden>
                <p>Some errors occured</p>
                <ul></ul>
            </div>

            <!-- Image Type -->
                <span id="type-image" class="type-media">
                    <div class="form-group">
                        <label class="col-sm-3 control-label">Title</label>
                        <div class="col-sm-9">
                            {{ Form::text('Image-title', null, array('class' => 'form-control', 'placeholder' => '')) }}
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-3 control-label">Choose file</label>
                        <div class="col-sm-9">
                            {{ Form::file('Image-file') }}
                            <p class="help-block">Only .jpg, .png, .gif, .bmp allowed.</p>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-3 control-label">Description</label>
                        <div class="col-sm-9">
                            {{ Form::textarea('Image-description', null, array('class' => 'form-control', 'rows' => '3')) }}
                        </div>
                    </div>
                </span>


            <div class="modal-footer">
                {{ Form::submit('Close', array('class' => 'btn btn-default', 'data-dismiss' => 'modal')) }}
                {{ Form::submit('Pin it, babe!', array('class' => 'btn btn-info')) }}
            </div>
            {{ Form::close() }}

Jquery

查询

addPin.on('submit', function() {
    event.preventDefault();
    var errorForm = addPin.find('div#validation-errors');
    $.ajax({
        url: '../public/posts/add',
        type: 'post',
        cache: false,
        data: addPin.serialize(),
        beforeSend: function() {
            errorForm.hide();
            errorForm.find("ul").empty();
        },
        success: function(data) {
            if(data.success == false) {
                var arr = data.errors;
                console.log(arr);
                $.each(arr, function(index, value){
                    if (value.length != 0){
                        errorForm.find("ul").append('<li>'+ value +'</li>');
                    }
                });
                errorForm.show();
                } else {
                location.reload();
            }
        },
        error: function() {
            alert('Something went to wrong.Please Try again later...');
        }
    });
    return false;
} );

PHP

PHP

public function postAdd(){
        if (Auth::check()){
                    $rules = array(
                        'Image-title' => 'Required|Min:3|Max:255|alpha_spaces',
                        'Image-description' => 'Required|Min:3',
                        'Image-file' => 'image',
                    );

            $validator = Validator::make(Input::all(), $rules);

            if ($validator->fails()) {
                return \Response::json(['success' => false, 'errors' =>  $validator->getMessageBag()->toArray()]);
            } else {
                        $post = Post::create(array(
                            'user_id'   => Auth::user()->id,
                            'title'     => Input::get('Image-title'),
                            'description' => Input::get('Image-description'),
                            'type'      => 'Image',
                        ));

                        $file = Input::file('Image-file');

                        $destinationPath    = 'img/';
                        $extension          = $file->getClientOriginalExtension();
                        $filename           = 'usr_'.  Auth::user()->id . '_post'.$post->id .'.'. $extension;

                        $file->move($destinationPath, $filename);
                        $post->imgLocation = $filename;
                        $post->save();

                DB::table('board_post')->insert(['board_id'  => 2, 'post_id'   => $post->id]);

                return  \Response::json(['success' => true]);//*/

            }
        }
    }

回答by nvisser

You should have an error in your app/storage/logs/laravel.logfile stating the exact error. Setting PHP to show all errors is preferable in a development environment tho, so you might want to consider turning those on, so you'll get a more descriptive message than just "500 Internal Server Error".

您的app/storage/logs/laravel.log文件中应该有一个错误,说明了确切的错误。设置 PHP 以显示所有错误在开发环境中更可取,因此您可能需要考虑将其打开,这样您将获得比“500 内部服务器错误”更具描述性的消息。

回答by Kiwi

The problem was due the fact that Jquery/JS don't really support Image upload

问题是由于 Jquery/JS 并不真正支持图片上传

I fixed the problem by when you click on the button, the form get's validated (via ajax) and show the errors when there are, otherwise it does the normal form sending (the one if I wouldn't do the event.prefentdefault())

我通过单击按钮解决了这个问题,表单得到验证(通过 ajax)并在有错误时显示,否则它会发送正常的表单(如果我不这样做的话event.prefentdefault()

this works for now, prehaps I'll have a second look at it to make it completly AJax, but probably not :)

这现在有效,我可能会再看看它以使其完全成为 AJax,但可能不是 :)

回答by Wistar

Check you upload_max_filesize in php.ini

Echo ini_get ("upload_max_filesize");

检查 php.ini 中的 upload_max_filesize

Echo ini_get ("upload_max_filesize");

See this

看到这个