使用knockout将图像源绑定到文件输入

时间:2014-07-16 07:15:03

标签: javascript knockout.js knockout-mvc

我有一个图像控件和文件输入控件,

   <img data-bind="attr:{src:Picture}">
     <span><i class="fa fa-edit"></i></span><input type="file" name="Picturefile" data-bind="value: Picture"></label>
 <div class="btn btn-group">
            <button type="submit" value="save" data-bind="click: editClient" class="btn btn-primary"><i class="fa fa-ok"></i>Save!</button>
            <a href="/admin/client" class="btn btn-info"><i class="fa fa-arrow-left"></i>Back to list</a>
        </div>

在编辑实体时,我想将当前图片与图像控件绑定,用户也可以使用文件控件编辑和选择新图片,

这是我的javascript,

<script type="text/javascript">
    $(function () {
        var ClientObject = {
            Name: "",
            Picture: ""

        }
        function Client(data) {
            var self = this;
            this.editClient = function () {
                var datatoPost = ko.mapping.toJS(self);
                $.ajax({
                    async: false,
                    method: 'post',
                    type: 'application/json',
                    url: '/api/my/client/',
                    data: datatoPost,
                    success: function (d) {
                        toastr.info("Saved");
                    }
                })
            }
            console.log('mapping to js',data);
            ko.mapping.fromJS(data, ClientObject, self);
        }

        var loadData = function (id) {
            var _url = '/api/v2/my/client';
            $.ajax({
                type: 'get',
                url: _url + '/' + id,
                success: function (d) {
                    if (!!d.error) { console.log(d.message); }
                    else {
                        var model = new Client(d);
                        ko.applyBindings(model, document.getElementById("clientCreate"));
                        console.log(model);
                    }
                }
            });
        }

        loadData(@ViewBag.Id);
    });
</script>

因此在加载时我收到以下错误:

Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string. 

淘汰赛的新手!!

1 个答案:

答案 0 :(得分:2)

我必须创建一个自定义绑定来完成它。我还没有完成任何跨浏览器测试,但我认为它适用于所有当前的浏览器。

<input type="file" data-bind="fileSrc: src" id="file"/>
<img data-bind="attr:{src:src}"/>

$(function() {
    ko.applyBindings(new ViewModel());
});

var ViewModel = function () {
    var self = this;

    self.src = ko.observable();
};

ko.bindingHandlers.fileSrc = {
    init: function (element, valueAccessor) {
        ko.utils.registerEventHandler(element, "change", function () {
            var reader = new FileReader();

            reader.onload = function (e) {
                var value = valueAccessor();
                value(e.target.result);
            }

            reader.readAsDataURL(element.files[0]);
        });
    }
};

http://jsfiddle.net/5vfKZ/1/