简体   繁体   中英

Uploading a default image in html form using javascript or jquery

Consider a html form which has different input fields in which one of them is of [type = file] and the user has to upload an image to it, and if the user does not upload an image and clicks submit, I like to update it with a default image of my own and then submit the form.

Does anyone know how to implement it?

Thanks in advance...

My current code looks like this

 if(document.getElementById("image") === "") { document.image.value="image.jpg"; }
 form { display: block; position: relative; } input { position:relative; margin-bottom:5px; }
 <form id="myform"> <input type="text" id="name" placeholder="Enter your name" required><br> <input type="email" placeholder="Enter your email" id="mail" required><br> <input type="file" accept=".jpg,.png" id="image"><br> <button type="submit">Submit</button> </form>

You should add a form submit event and check the length of files of the input[type="file"] inside the event handler function:

document.querySelectior("#myform").addEventListener('submit', function() {
    if (document.getElementById("image").files.length == 0) {
        document.img.value="image.jpg";
    }
});

// HTML

<form id="myform">
      <input type="text" name="username" id="name" placeholder="Enter your name" required><br>
      <input type="email" name="email" placeholder="Enter your email" id="mail" required><br>
      <input type="file" name="image" accept=".jpg,.png" id="image"><br>
      <button type="submit">Submit</button>
     </form>

// Javascript

let defaultFileImage = null;
let url = 'image.jpg';

// convert url image to File object
fetch(url)
  .then(res => res.blob())
  .then(blob => {
    defaultFileImage = new File([blob], 'image.jpg', blob)
  });

  // submit form
  document.getElementById('myform').addEventListener('submit', (e) => {
    e.preventDefault();

    var myform = document.forms.myform;
    var formData = new FormData(myform);
    var userImage = formData.get('image');
    
    if(userImage.name) {      
      console.log(userImage)
    }
    else {
      console.log(defaultFileImage)
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM