2017-09-06 67 views
0

我有一個HTML形式,其允許用戶上載的圖像,這樣將它提交給從SRC的值在<img>標籤獲取的圖像,並通過javascript

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

我的問題是:

i)如何選擇HTML(img)標記中的圖像,並在type =「file」的輸入元素上使用javascript進行選擇並提交表單,而無需用戶填寫並單擊什麼?

或者爲了理解我的問題,假設你在value =「」中嵌入了一個文件。 將帖子

回答

0

這將取決於這個地方的圖像從何而來。如果從不同的出身,你是有點卡住,否則,

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')); 

這裏我使用ES6語法和fetch API,但同樣可以用XHR來完成。
關於FormData的文檔。

0

出於安全原因,你不能設置默認輸入[類型=「文件」]

+0

我可以通過HTTP請求發送圖像嗎? – teachm3