简体   繁体   中英

Upload images using only Javascript or nodejs for client-side modification?

So I'm making a website as a tool people can use to generate some cards. Users have the option to upload their own backside of all the cards. However I can't find out how to allow them to upload their images.

I don't want to save the uploaded image to the server, only have access to it client side.


I've looked and found many that use jQuery (don't have it, nor have I used it before).
<input type="file"> Doesn't work as it won't stay inside a select. <select><option><input type="file"></option></select> (displays outside the select, can't seem to fix that)
And even more that saves the img to the server. (I want it all client-side)

I'm using browserify so NodeJS modules work, but the few I've found require an <input type="file"> . I'd share what I've tried, but I've only tried using the <input> method, and it failed and I don't know what else todo.

My end goal is to:

  1. Upload image (can't figure out).
  2. Copy image onto a pdf.
  3. Allow user to download pdf.
  4. Have it all client side so server doesn't need to stress itself.

https://hacks.mozilla.org/2011/01/how-to-develop-a-html5-image-uploader/

You might want to read the above document and modify it according to your needs

So I found this answer via a link inside a link inside the link @Mukund Goel's anwser (bunny trail). However I'm not accepting Mukund's due to the fact his answer didn't solve my problem.

So I found out what I needed by this: link I totally didn't think to use a hidden <input> tag.

So all I need todo is do this:
( I'd make this a snippet but this doesn't work in snippets due to the need of <input type="file"> )

    let hiddenInput = document.getElementById('hidden');
    let result = document.getElementById('result');
    let img = document.getElementById('result');
    document.getElementById('bttn').onclick = hiddenInput.click;
    document.getElementById('sel').onchange = hiddenInput.click;
    hiddenInput.onchange = function() {
      let file = this.files[0];
      if (!file.type.startsWith('image/')) return;
      const reader = new FileReader();
      reader.onload = (function(aImg) {
        return function(e) {
          aImg.src = e.target.result;
        };
      })(img);
      reader.readAsDataURL(file);
    }

    <input type="file" style="display:none" accept="image/*" id="hidden">
    <button id="bttn">Click Me</button>
    <select id="sel">
      <option>Or change me</option>
      <option>Choose me</option>
    </select>
    <img id="result">

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