How To Implement File Upload With Drag And Drop In Vanilla JS?

Asked 11 months ago
Answer 1
Viewed 498
1

I expounded on the Simplified Programming interface ideas before.

Presently I need to show how I executed a basic document transfer with simplified on a site I'm building.

How To Implement File Upload With Drag And Drop In Vanilla JS?

Distinguish a HTML component you maintain that individuals should drag their documents to:

  class="dropzone"
  ondragover=`dragOverHandler(event)`
  ondragleave=`dragLeaveHandler(event)`
  ondrop=`dropHandler(event)` 
>
...

ondragover is terminated when individuals are hauling a document on the component. We can utilize this to add some style, for instance a ran line.

ondragleave is the inverse, when we leave the drop region.

I utilized this JS to add a dragging_over class to the component, and style it with CSS:

function dragOverHandler(event) {
  event.preventDefault();
  const dropzone = document.querySelector('#dropzone');
  dropzone.classList.add('dragging_over');
}

function dragLeaveHandler(event) {
  event.preventDefault();
  const dropzone = document.querySelector('#dropzone');
  dropzone.classList.remove('dragging_over');
}

#dropzone.dragging_over {
  border: 2px dashed #fff;
  background-color: #666;
}

 

ondrop is terminated when the record (or various documents!) is dropped on the area.

That is where the activity occurs.

I assemble the documents, check they're pictures (I just need pictures in this model), and POST the information to/programming interface/transfer:

async function dropHandler(event) {
  event.preventDefault()

  const endpoint = `/api/upload`

  if (event.dataTransfer.items) {
    const formData = new FormData()
    formData.append('action', 'upload')

    for (let item of event.dataTransfer.items) {
      if (item.kind === 'file') {
        const file = item.getAsFile()
        if (file) { 
          //I only want images
          if (!file.type.match('image.*')) {
            alert('only images supported')
            return
          }
          formData.append('files', file)
        }
      }
    }

    try {
      const response = await fetch(endpoint, {
        method: 'POST',
        body: formData,
      })

      if (response.ok) {
        console.log('File upload successful')
      } else {
        console.error('File upload failed', response)
      }
    } catch (error) {
      console.error('Error uploading file', error)
    }
  }
}

How to handle that server-side depends on your server.

With Astro I got the data using:

 

const formData = await Astro.request.formData()

console.log(formData.getAll('files'))

FAQs

How do you implement drag and drop upload?

You can drag the documents or envelopes from record adventurer and drop into the drop region. As a matter of course, the Uploader part go about as drop region component. The drop region gets featured when you drag the documents over drop region. The Uploader part permits you to set outside target component as drop region utilizing the dropArea property.

How to upload a file using HTML and JavaScript?

With HTML, to get to a record on the client's gadget, we need to utilize a <input> with the "document" type . Furthermore, to make the HTTP solicitation to transfer the record, we need to utilize a <form> component. While managing JavaScript, the initial segment is still evident. We actually need the document contribution to get to the records on the gadget.

How to move uploaded file to folder in JavaScript?

The move_uploaded_file() capability moves a transferred record to another area. This capability returns Valid on record fruitful transferred, or Misleading on document transfer blunder. This capability checks to guarantee that the document assigned by filename is a legitimate transfer record.

How to upload file and store in local folder in JavaScript?

files[0]; let passage = archive. getElementById("file"). files[0]; console. log('doupload',entry,data) fetch('uploads/' + encodeURIComponent(entry.name), {method:'PUT',body:data}); alert('your record has been transferred'); area.

Read Also : How do you wish someone a happy festive season professionally?
Answered 11 months ago White Clover   MarketsWhite Clover Markets