图像在Node.js中拖放和上传

时间:2017-03-04 15:19:48

标签: javascript jquery node.js drag-and-drop image-uploading

我正在使用node.js,express,mongoose。

我有一个允许用户使用的表单 1.单击“上载图像”并上传图像 2.将图像从计算机拖到保管箱中以上传图像

  1. 按预期工作。我遇到了麻烦2.基本上,我可以将图像放入dropzone,但提交表单时,图像实际上从未上传。我读了很多,但似乎无法找到解决方案。
  2. 我知道dropzone.js,但决定不使用它只是为了学习如何自己做。

    这就是我的Dropbox的样子(只是让你理解代码): enter image description here

    基本上,当用户点击上传或将图片拖放到保管箱中时,它会显示在预览中。这很有效。

    以下是我的代码的相关部分:

    new.ejs

    <input name="image" type="file" id="image" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
    
       <div id="imageBorder" >
            <div id="imageContainer">
    
                 <div id="dropbox">
                       <i class="fa fa-picture-o" aria-hidden="true"></i>
                        <p> Drop image here or click to upload</p>
                 </div>
    
                 <div id="preview" class="hidden">
                 </div>
    
                 <button id="fileSelect" class="btn btn-primary btn-block">Upload Image</button>
                <button id="fileRemove" class="btn btn-primary btn-block">Remove Image</button>
    
    </div>
    

    eventform.js

    function eventImageSetup() {
    
    var dropbox = document.getElementById("dropbox"),
        fileElem = document.getElementById("image"),
        fileSelect = document.getElementById("fileSelect"),
        fileRemove = document.getElementById("fileRemove");
    
    $(dropbox).height($('#imageBorder').height());
    
    fileSelect.addEventListener("click", function(e) {
        if (fileElem) {
          fileElem.click();
          e.preventDefault(); // to prevent submit
        }
    }, false);
    
    fileRemove.addEventListener("click", function(e) {
        e.preventDefault(); // prevent submit
        if(!$('#preview').hasClass('hidden')) { // If there is an image uploaded
            $('#preview').empty(); 
            $('#dropbox').removeClass('hidden');
            $('#preview').addClass('hidden');
            $('#fileSelect').text('Upload Image');
            resetFileInputField();
        }
        removeError($('#imageError'), $('#image'));
    });
    
    dropbox.addEventListener("dragenter", dragenter, false);
    dropbox.addEventListener("dragover", dragover, false);
    dropbox.addEventListener("drop", drop, false);
    
    } // end of eventImageSetup
    
    
    function dragenter(e) {
      e.stopPropagation();
      e.preventDefault();
    }
    
    function dragover(e) {
      e.stopPropagation();
      e.preventDefault();
    }
    
    function drop(e) {
      e.stopPropagation();
      e.preventDefault();
      var dt = e.dataTransfer;
      var files = dt.files;
      handleFiles(files);
    }
    
      function handleFiles(files) { 
    
    
        var file = files[0];
    
        console.log("This is the file: ", file);
    
        var imageType = /^image\//;
        if (!imageType.test(file.type)) {
          // a bunch of code to deal with this...
          return;
       } else if (file.size > MAX_FILE_SIZE) {
          // a bunch of code to deal with this..
         return; 
     } else {
    
          var img = document.createElement("img");
          img.onload = function() {
                adjustImageSize(img);
          };
          $('#dropbox').addClass('hidden');
          $('#preview').removeClass('hidden');
          $('#preview').empty();
          $('#preview').append(img);
          $('#fileSelect').text('Replace Image');
          var reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = function(event) {
              img.src = event.target.result;
          }
      }
    }
    

    正如您所看到的,问题是在拖放时,我实际上从未将文件附加到表单元素。我尝试将文件附加到$('#image')。文件,但显然你无法解决安全问题。基本上我继续阅读我无法以编程方式添加文件。

    任何指导都将不胜感激......

1 个答案:

答案 0 :(得分:0)

如果我没有弄错的话,您必须附上onload事件before才能阅读该文件。

  var reader = new FileReader();
  reader.onload = function(event) {
      img.src = event.target.result;
  }
  reader.readAsDataURL(file);

示例

&#13;
&#13;
var MAX_FILE_SIZE = Infinity; // ignore this

function eventImageSetup() {

  $(dropbox).height($('#imageBorder').height());

  fileSelect.addEventListener("click", function() {
    image.click();
  }, false);

  fileRemove.addEventListener("click", function() {
    if (!$('#preview').hasClass('hidden')) { // If there is an image uploaded
      $('#preview').empty();
      $('#dropbox').removeClass('hidden');
      $('#preview').addClass('hidden');
      $('#fileSelect').text('Upload Image');
      resetFileInputField();
    }
    removeError($('#imageError'), $('#image'));
  }, false);

  dropbox.addEventListener("dragenter", dragenter, false);
  dropbox.addEventListener("dragover", dragover, false);
  dropbox.addEventListener("drop", drop, false);

} // end of eventImageSetup


function dragenter(e) {
  e.stopPropagation();
  e.preventDefault();
}

function dragover(e) {
  e.stopPropagation();
  e.preventDefault();
}

function drop(e) {
  e.stopPropagation();
  e.preventDefault();
  var dt = e.dataTransfer;
  var files = dt.files;
  handleFiles(files);
}

function handleFiles(files) {


  var file = files[0];

  //console.log("This is the file: ", file);

  var imageType = /^image\//;
  if (!imageType.test(file.type)) {
    // a bunch of code to deal with this...
    return;
  }
  if (file.size > MAX_FILE_SIZE) {
    // a bunch of code to deal with this..
    return;
  }
  var img = document.createElement("img");
  img.onload = function() {
    //adjustImageSize(img);
  };
  $('#dropbox').addClass('hidden');
  $('#preview').removeClass('hidden');
  $('#preview').empty();
  $('#preview').append(img);
  $('#fileSelect').text('Replace Image');
  var reader = new FileReader();
  reader.onload = function(e) {
    img.src = e.target.result;
  }
  reader.readAsDataURL(file);
}

eventImageSetup();
&#13;
#dropbox {
  border: 2px dashed;
  height: 100px;
  width: 230px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="image" type="file" id="image" accept="image/*" style="display:none" onchange="handleFiles(this.files)">

<div id="imageBorder">
  <div id="imageContainer">

    <div id="dropbox">
      <i class="fa fa-picture-o" aria-hidden="true"></i>
      <p> Drop image here or click to upload</p>
    </div>

    <div id="preview" class="hidden">
    </div>

    <button id="fileSelect" type="button" class="btn btn-primary btn-block">Upload Image</button>
    <button id="fileRemove" type="button" class="btn btn-primary btn-block">Remove Image</button>

  </div>
&#13;
&#13;
&#13;

旁注

  • 可以使用ID值在JavaScript中引用具有ID属性(不包含任何破折号)的元素。例如,可以使用<input id="fileSelect">代替fileSelect来访问document.getElementById('fileSelect')
  • type="button"的按钮元素不会在点击时提交表单。