【问题标题】:Image do not show after choosing file from browse button从浏览按钮选择文件后图像不显示
【发布时间】:2014-02-26 08:30:08
【问题描述】:

我正在使用 laravel 4,我使用 Form::file('image') 上传和存储图像。 它工作正常。但是当我点击浏览按钮时,它只显示上传的图片名称。我想显示上传的图像。

    {{ Form::open(array('route'=>'speaker.store','files' => 'true')) }}
    {{ Form::label('image','Image') }}
    {{ Form::file('image') }}
    {{ Form::submit('Save') }}
    <a href="{{ URL::route('speaker.index') }}">Cancel</a>
{{ Form::close() }}

为了更新表单,显示旧图像,我想显示新浏览的图像。

 {{ Form::model($speaker,array('route' =>array('speaker.update',$speaker->id),'method' => 'post','files' => true)) }}
    <img alt="{{ $speaker->name }}" src="{{ URL::to($speaker->image) }}">
    {{ Form::file('image') }}

    {{ Form::submit('Update') }}

    <a href="{{ URL::route('speaker.index') }}">Cancel</a>

{{ Form::close() }}

【问题讨论】:

    标签: javascript image forms


    【解决方案1】:

    当然不是。这是浏览器的默认行为。

    你必须使用 JavaScript 来做这个客户端。


    Form::file提供ID

    {{ Form::file('image', array('id' => 'image-input')) }}
    


    然后在此元素上注册change 事件的处理程序。

    document.getElementById('image-input').addEventListener('change', handleFileSelect, false);
    


    创建 handleFileSelect 函数,它可以满足您的需求。

    function handleFileSelect(evt)
    {
        var files = evt.target.files; // FileList object
    
        // Loop through the FileList and render image files as thumbnails.
        for (var i = 0, f; f = files[i]; i++)
        {
            // Only process image files.
            if (!f.type.match('image.*')) {
                continue;
            }
    
            var reader = new FileReader();
    
            // Closure to capture the file information.
            reader.onload = (function(theFile) {
                return function(e) {
                    // Render thumbnail.
                    var image = document.createElement('img');
                    image.src = e.target.result;
    
                    document.body.appendChild(image);
                };
            })(f);
    
            // Read in the image file as a data URL.
            reader.readAsDataURL(f);
        }
    }
    

    您可能想要更改 image 的附加位置或其他内容...

    请记住,浏览器必须支持 HTML5 File API(此处为 FileReader 和 FileList)才能在本地读取文件。

    我是即时写的,对于语法错误或类似问题,我深表歉意。

    【讨论】:

    • 我完全忘了考虑浏览器的默认行为。我不习惯前端开发。谢谢你的回答。
    • 是的,我愿意,但我尝试使用该代码,但它不起作用。无论如何,谢谢。
    • 什么不起作用?确实如此,但看起来您懒得根据需要对其进行修改。
    • 我说我尝试在我的项目中使用它,但它不适合我的代码。我知道我需要更多地了解前端开发,所以我决定先完成后端,然后再去前端。因此,如果您不完全了解,请不要标记。
    猜你喜欢
    • 2015-09-20
    • 2010-11-25
    • 2015-08-27
    • 2015-02-16
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 2013-04-25
    • 1970-01-01
    相关资源
    最近更新 更多