使用knockout js上传文件

时间:2015-01-15 06:44:33

标签: javascript c# knockout.js

使用knockout js无法正常上传文件。我试过下面的代码,但没有工作。请提一下我做错的地方。

这是我的文件控件和按钮。我无法将所选文件从客户端发送到服务器。请建议最好的方法是什么。

<input id="files" name="files" type="file" class="input-file" data-bind="file: FileProperties.FileName"/> 
<button data-bind="click : Upload">Upload</button>

<script type="text/javascript">

    ko.bindingHandlers.file = {
        init: function (element, valueAccessor) {
            alert('init');
            $(element).change(function () {
                var file = this.files[0];
                if (ko.isObservable(valueAccessor())) {
                    valueAccessor()(file);
                }
            });
        }
</script>

5 个答案:

答案 0 :(得分:21)

我为我当前的项目提出了这个解决方案。

<img class="myImage" data-bind="attr: {src: $root.photoUrl() || 'images/tempImage.png'}"/>
<input data-bind="event: {change: $root.fileUpload}" type="file" accept="image/*" class="fileChooser"/>

<script>
var myController = function()
{
    var self = this;
    this.photoUrl = ko.observable();      
    this.fileUpload = function(data, e)
    {
        var file    = e.target.files[0];
        var reader  = new FileReader();

        reader.onloadend = function (onloadend_e) 
        {
           var result = reader.result; // Here is your base 64 encoded file. Do with it what you want.
           self.photoUrl(result);
        };

        if(file)
        {
            reader.readAsDataURL(file);
        }
    };
};
</script>

答案 1 :(得分:4)

好像你需要一个自定义的敲除绑定文件上传。有各种api / lib可用于处理所有具有附加功能的错误情况。 试试这个: https://github.com/TooManyBees/knockoutjs-file-binding

答案 2 :(得分:2)

<input type="file" id="FileName" style="width:180px" data-bind="value:addModel.InputFileName" />

function ()
{
    var files = $("#FileName").get(0).files;
    var data = new FormData();
    for (var x = 0; x < files.length; x++) {
        data.append("file" + x, files[x]);
    }

    $.ajax({
        type: "POST",
        url: '/api/Controller' + '/?id=' + id ),
        contentType: false,
        processData: false,
        data: data,
        success: function (result) {},
        error: function (xhr, status, p3, p4) {}
    });
}

答案 3 :(得分:0)

您可以执行以下操作:

查看:

<input type="file" id="files" name="files[]" multiple data-bind=" event:{change: $root.fileSelect}" />
<output id="list"></output>

<ul>    
    <!-- ko foreach: files-->
    <li>
        <span data-bind ="text: name"></span>: <img class="thumb" data-bind = "attr: {'src': src, 'title': name}"/>
    </li>
    <!-- /ko -->  
</ul>

JS:

var ViewModel = function() {
    var self = this;     
    self.files=  ko.observableArray([]);
    self.fileSelect= function (elemet,event) {
        var files =  event.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) {                             
                  self.files.push(new FileModel(escape(theFile.name),e.target.result));
              };                            
          })(f);
          // Read in the image file as a data URL.
          reader.readAsDataURL(f);
        }
    };
};

var FileModel= function (name, src) {
    var self = this;
    this.name = name;
    this.src= src ;
};

ko.applyBindings(new ViewModel());

您可以在链接中找到该演示: http://jsfiddle.net/fPWFd/436/

答案 4 :(得分:0)

对于下面的Magento 2,代码可用于通过剔除js显示上传的图片。

在html文件中

 <img class="myImage" data-bind="attr: {src: photoUrl() || 'images/tempImage.png'}"/>
 <input data-bind="event: {change: fileUpload}" type="file" accept="image/*" class="fileChooser"/>

js文件需要进行以下编码

 define(['ko', 'uiComponent', 'jquery'], function (ko, Component, $) {
   'use strict';
    var photoUrl;
    return Component.extend({
      photoUrl : ko.observable(),
      fileUpload: function(data, e)
       {
          var file    = e.target.files[0];
          var reader  = new FileReader();
          reader.onloadend = function (onloadend_e)
          {
            var result = reader.result; // Here is your base 64 encoded file. Do with it what you want.
            self.photoUrl(result);
          };
          if(file)
          {
            reader.readAsDataURL(file);
          }
        },
      });
  });
}

以上代码在我的项目中运行正常。