Search code examples
javascriptjqueryhtmlgoogle-chrome-extensionfirefox-addon

Allow user to upload images on x folder chrome extension without submit button


I want to allow the user to upload images on chrome extension example folder name (upload) and without submit button

<form action="/upload">
  <input type="file" name="myimages" accept="image/*">
</form>

show images

<span class="AvGbtn" id="AvBgIds" style="background-image: url(Here i want to show upload images url
); background-size: 100% 100%;" oncontextmenu="return false">  
</span>

Solution

  • $( document ).ready(function() {
        $( '#myimages' ).change(function() {
          var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '');
          $( '#myform' ).submit();
          $( '#uploaded').append('<img src="/upload/' + filename + '"/>');
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <form id="myform" action="/upload">
      <input type="file" name="myimages" id="myimages" accept="image/*">
    </form>
    <div id="uploaded">
    </div>

    Use the onchange event of the file upload field to submit the form.

    EDIT:

    Added functionality to display the uploaded image in the div below the form.

    Credits: Use jQuery to get the file input's selected filename without the path