从浏览按钮选择文件后,图像不显示

时间:2014-02-26 08:30:09

标签: javascript image forms

我正在使用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() }}

1 个答案:

答案 0 :(得分:0)

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

您必须使用JavaScript执行此客户端。


将ID提供给Form::file

{{ 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文件API(此处为FileReader和FileList)才能读取文件。

我已经写好了,抱歉语法错误或类似。

相关问题