直接文件上传Javascript

时间:2018-03-04 17:47:49

标签: javascript jquery

如何直接上传文件而不点击文件上传按钮(我想点击添加小工具按钮,这应该给文件上传对话框)

我有一个声明如下的按钮:

<button class="add-button" style="float:top;">Add Widget</button>

单击按钮时,将调用以下函数

    $(".add-button").on("click", function() {


  // get selected color value
  var color = $color_picker.val();

  // build the widget, including a class for the selected color value
  var $widget = $('<li>', {
      'class': 'color_' + color
    })
    .append($('<button>', {
      'class': 'delete-button',
      'text':'-'
    }))
    .append($('<img src="abc.png" height="60px" width="60px">'));

  // add widget to the grid
  gridster.add_widget($widget, 1, 1);

});

但我首先想要一个上传框出现在用户可以在单击按钮后立即上传图像的位置,然后上述代码将被执行

我做了类似的事

 $(".add-button").on("click", function() {

    var x = document.createElement("INPUT");
     x.setAttribute("type", "file");
     x.setAttribute("onclick","previewFile()");



  // get selected color value
  var color = $color_picker.val();

  // build the widget, including a class for the selected color value
  var $widget = $('<li>', {
      'class': 'color_' + color
    })
    .append($('<button>', {
      'class': 'delete-button',
      'text':'-'
    }))
    .append($('<img src="abc.png" height="60px" width="60px">'));

  // add widget to the grid
  gridster.add_widget($widget, 1, 1);

});

但这并没有带来任何用户可以上传图片的对话框

我想要在

位置使用这个上传的图像
    .append($('uploaded image'));

预览文件功能(这也需要修改)

function previewFile() {
  var preview = document.createElement('img');

  var file    = document.querySelector('input[type=file]').files[0];
  var reader  = new FileReader();    //API for reading file stored on user computer

  reader.addEventListener("load", function () {    //"load" :This eventlisterner "listens" loading of file. Once it is loaded function is triggered
    preview.src = reader.result;   
  });

  if (file) {
    reader.readAsDataURL(file);    // helps in reading the content of "file"
  }


  document.body.appendChild(preview);
}

我的目标是预览文件功能应该返回一个我可以放入的图像

    .append($('image from preview file'));

代码版本位于Fiddle

1 个答案:

答案 0 :(得分:1)

这样做的方法是在dom上的某处有一些隐藏的输入文件类型。你可能能够以编程方式将它放在那里,但实际上没有任何意义。单击添加小部件按钮后,您可以模拟隐藏输入的单击。这将启动选择文件的提示。那么你想要做的是,等到文件被用户“挑选”。这是通过onchange事件完成的。在其中,您可以获取文件,阅读它,然后在完成后,您可以通过onload方法进行回调。我在这里贴了一个working example。我想你想把文件作为src上的图像设置选中,所以我也这样做了。

隐藏输入

    <input id="test" type="file" style="position: absolute; top: -10; left: -10; height: 0; width: 0;" />

按钮单击功能(这将等到文件被选中之后),回调方法用于文件阅读器的onload事件。

$(".add-button").on("click", function() {

    $('#test').click();

  $('#test').on('change', function(e) {
    var test = document.getElementById('test');

    if (!test) {
      alert("Um, couldn't find the fileinput element.");
    }
    else if (!test.files) {
      alert("This browser doesn't seem to support the `files` property of file inputs.");
    }
    else if (!test.files[0]) {
      alert("Please select a file before clicking 'Load'");               
    }
    else {
      file = test.files[0];
      console.log(file);
      fr = new FileReader();
      fr.readAsDataURL(file); 
      fr.onload = function() {
        var data = fr.result;  // data <-- in this var you have the file data in Base64 format
        callbackAddButton(data);
        test.value = ''; //here we are resetting the file input's files
        $('#test').replaceWith($('#test').clone()); //here we are resetting the input, if we clone the input with the files then it wont trigger the onchange event if you upload same image. So we need to make sure we have these 2 calls. 
      };
    }
  })
});

最后,回调方法。这正是您之前所拥有的,但现在只有在文件完成后才会被调用(完成后,通过文件读取器读取,并在需要时访问内容)。现在唯一的区别是你有一个用户上传的图像的base64表示。我正在设置您创建的新图像窗口小部件。

 function callbackAddButton(file) {
 // get selected color value
  var color = $color_picker.val();

  // build the widget, including a class for the selected color value
  var $widget = $('<li>', {
      'class': 'color_' + color
    })
    .append($('<button>', {
      'class': 'delete-button',
      'text':'-'
    }))
   .append($(`<img src="${file}" height="60px" width="60px">`));

  // add widget to the grid
  gridster.add_widget($widget, 1, 1);
}

修改 一旦你完成了输入文件元素,现在清除它是一个好习惯,因为你不再需要文件了(至少从输入开始,因为你有一个base64表示)。只需在进行回拨呼叫后添加$('#test').replaceWith($('#test').clone())即可。