JavaScript method to determine the type of file to upload

  • 2020-03-30 03:50:07
  • OfStack

This example shows how JavaScript can determine the type of file to upload, which is a very common technique. The specific implementation method is as follows:

File upload using a function, using the HTML element of the input tag:


<input id="imageFile" name="imageFile1" accept="image/jpg,image/jpeg,image/png,image/bmp,image/gif" type="file"   title=" I'm gonna hit select file " onchange="imageSubmit(this,0);"/> 

The onchange event will be triggered immediately after the selected picture to upload the picture, but the repeated selection of the same picture will not trigger the onchang event. The solution is as follows:


function imageSubmit(obj, imageType) { 
  if (imageType == "0") { 
  //Related processing code...

  //Resolve uploading the same picture without triggering the onchange event
  var nf = obj.cloneNode(true);
  nf.value=''; 
  obj.parentNode.replaceChild(nf, obj);
  }
}

The cloneNode() method is used to create an identical copy of the node that is called, with the parameter true for deep replication, i.e. copying the node and the entire child tree, and with the parameter false for shallow replication, i.e. copying only the node itself. The copy of the node returned after the copy is owned by the document, but no parent node is specified for it. Thus, this copy of the node becomes an "orphan" unless it is added to the document by appendChild(), insertBefore(), or replaceChild().


Related articles: