将HTML粘贴板中的图像转换为文件输入

32

好的,让我们开始吧。我看到了一些非常好的方法可以将图片粘贴到 WhatsApp 网页聊天中。大多数示例使用画布来捕获粘贴的剪贴板图片,但是如何使用 仅通过在页面上按 Ctrl + V 把它粘贴到文件输入框中呢?

这里是我自动提交所选文件的输入框代码:

      <form id="new_document_attachment" method="post">
            <div class="actions"><input type="submit" name="commit" value="Submit" /></div>
                <input type="file" id="document_attachment_doc" />
      </form>
      <script>
          document.getElementById("document_attachment_doc").onchange = function() {
          document.getElementById("new_document_attachment").submit();
        };
      </script>
3个回答

69
这很简单。只需在window对象上捕获paste事件,并将从中获取的所有文件放入<input>标签中即可。

const form = document.getElementById("new_document_attachment");
const fileInput = document.getElementById("document_attachment_doc");

fileInput.addEventListener('change', () => {
  form.submit();
});

window.addEventListener('paste', e => {
  fileInput.files = e.clipboardData.files;
});
<form id="new_document_attachment" method="post" enctype="multipart/form-data">
  <div class="actions"><input type="submit" name="commit" value="Submit" /></div>
  <input type="file" name="document_attachment_doc" id="document_attachment_doc" />
</form>


2
谢谢! 太棒了! - doer123456789
2
供参考,如果您想知道,根据 https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent/clipboardData,所有主要的桌面和移动浏览器都支持此功能。 - A. Genedy
另外,jQuery 的等效代码是 e.originalEvent.clipboardData.files - EgoistDeveloper
1
我尝试使用macOS的“屏幕截图到剪贴板”功能进行粘贴。这会返回一个{"error":"key missing: title"}消息。我能做些什么吗? - FBI Surveillance Van

1
我只想补充一点,对于上述示例代码能够正常工作,我实际上必须将 enctype="multipart/form-data" 属性添加到表单元素中。

1
你用的是哪个浏览器?我一直使用建议的答案多年,没有任何问题。 - doer123456789
1
Firefox。似乎在上传文件时需要使用multipart/form-data enctype。至少根据https://www.w3schools.com/TAGs/att_form_enctype.asp的说法:“multipart/form-data不编码任何字符。当您使用具有文件上传控件的表单时,需要此值”。也许Chrome会自动切换到所需的enctype或其他什么操作? - Vaclav Masin
现在在Edge 115.0.1901.203(最新稳定版)上进行了测试,我的表单没有使用enctype="multipart/form-data"也无法正常工作。这真的很有趣 :) - MetropolisCZ

-1

工作良好

<form action="abc.php" method="post" enctype="multipart/form-data">
  <div class="actions"><input type="submit" name="commit" value="Submit" /></div>
  <input type="file" name="aaa"/>
</form>
  
 <script type="text/javascript">
//e.originalEvent.clipboardData.files
const form = document.getElementById("new_document_attachment");
const fileInput = document.getElementById("document_attachment_doc");

fileInput.addEventListener('change', () => {
  form.submit();
});

window.addEventListener('paste', e => {
  fileInput.files = e.clipboardData.files;
}); 
 </script>

PHP输出:var_dump($_FILES);

array (size=1)
  'aaa' => 
    array (size=5)
      'name' => string 'image.png' (length=9)
      'type' => string 'image/png' (length=9)
      'tmp_name' => string 'C:\wamp64\tmp\phpF6AF.tmp' (length=25)
      'error' => int 0
      'size' => int 9380

不确定为什么你“改写”了得到60票的答案,但是你的答案并不起作用,并且出现了“TypeError: Cannot read properties of null (reading 'addEventListener')”的错误。 - Steve Payne

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接