简体   繁体   中英

Getting an image from value of src in <img> tag and submitting it to <input type=“file”> via javascript

I have a HTML form that allows an user to upload an image, like this:

    <form method="POST" action="/somewhere">
    <input type="file" />
    <input type="submit" />
    </form>

My question is:

i) How to choose an image that's in html(img) tag and select it at input element with type="file" only using javascript and submit the form without user having to fill out and click anything?

Or to understand my question, assume that you're embedding a file in value="". [EDITED]

出于安全原因,您不能为input [type =“ file”]设置默认值

That will depend on where this image comes from. If from a different origin, you're kinda stuck, otherwise,

fetch(img.src) // fetch the image resource
  .then(r => r.blob()) // as blob
  .then(blob =>{
    cont form = new FormData(); // create a FormData
    form.append('file', blob, filename); // add the blob, I let you define the filename
    // post it to your server
    return fetch('/somewhere', {method:'POST', body:form});
  }).then(r => console.log('sent'));

Here I am using ES6 syntax and fetch API , but same could be done with XHR .
Docs on FormData .

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