jeudi 18 juin 2020

Can I use custom image upload as the provided code below?

I try to write a custom image file uploader and preview using HTML, CSS, javascript. There is confusion. I searched for examples code on google and those code examples are far more complex and many lines of code. So I'm thinking that is my approach to that problem not secured for end-user? Please check my front-end js code. Backend code is almost right with nodejs and express.

Html(using EJS) code here!

      <div class="form-group">
        <label for="image">Image</label>
        <div class="file-container">
          <div class="file-wrapper">
            <input
              type="file"
              class="file-input"
              id="image"
              name="image"
              accept="image/*"
              required
            />
            <div class="file-content">
              <div class="file-infos">
                <p class="file-icon">
                  <i class="fas fa-file-upload fa-7x"></i>
                  <span>Click to browse or drop file here.</span>
                </p>
              </div>
              <p id="js-file-name" class="file-name">No file selected.</p>
            </div>
          </div>
        </div>
      </div>

CSS code here!

:root {
  --overlay-color: rgba(0, 0, 0, 0.7);
  --dialog-color: #e9ecef;
  --dialog-border-radius: 5px;
  --icon-color: rgba(73, 80, 87, 0.6);
  --dialog-padding: 20px;
  --drag-over-background: #e3e5e8;
}

.file-container {
  font-family: sans-serif;
  font-size: 13pt;
  color: #4d4d4d;
  text-align: center;
}

.file-wrapper {
  height: auto;
  margin: auto;
  border: 1px solid #cacdd0;
  border-radius: var(--dialog-border-radius);
  padding: var(--dialog-padding);
  position: relative;
}

.file-wrapper:hover {
  border: 4px solid #00abff54;
}

.file-input {
  width: 100%;
  height: 100%;
  background-color: #000;
  cursor: pointer;
  opacity: 0;
  position: absolute;
  z-index: 2;
  left: 0px;
  top: 0px;
}

.file-content {
  position: relative;
  display: block;
  width: 100%;
  height: 100%;
  margin: auto;
  transition: 0.2s;
}

.file-icon > span {
  display: block;
}

.has-drag {
  display: inline;
}

.file-name {
  font-weight: bold;
  font-size: 15pt;
}

JS code here!

let image = document.querySelector('#image');
let fileName = document.querySelector('#js-file-name');
let imageCont = document.querySelector('.file-icon');
image.addEventListener('change', () => {
  if (image.files[0]) {
    let url = URL.createObjectURL(image.files[0]);
    fileName.innerHTML = image.files[0].name;
    imageCont.innerHTML = `<img src="${url}" class="preview" />`;
  } else {
    fileName.innerHTML = `No file selected.`;
    imageCont.innerHTML = `<i class="fas fa-file-upload fa-7x"></i>
      <span
        >Click to browse
        <span class="has-drag">or drop file here</span></span
      >`;
  }
});



Aucun commentaire:

Enregistrer un commentaire