更新于 2025-10-03
可以使用 JavaScript 的 Clipboard API 获取文件(如图片、文本等),然后用 FormData 进行上传。
下面是常见的实现思路:
document.addEventListener('paste', async function (event) {
// 检查粘贴板中是否有文件
const items = event.clipboardData.items;
for (const item of items) {
if (item.kind === 'file') {
const file = item.getAsFile();
uploadFile(file); // 调用上传函数
}
// 如果你想处理文本,可以这样:
if (item.kind === 'string') {
item.getAsString(text => {
// 可以把文本转为 Blob 后上传
const blob = new Blob([text], { type: 'text/plain' });
const file = new File([blob], 'clipboard.txt', { type: 'text/plain' });
uploadFile(file);
});
}
}
});
function uploadFile(file) {
const formData = new FormData();
formData.append('file', file); // 'file' 是表单字段名
fetch('/your-upload-url', {
method: 'POST',
body: formData
})
.then(res => res.json())
.then(data => {
console.log('上传成功', data);
})
.catch(err => {
console.error('上传失败', err);
});
}
multipart/form-data
格式的文件上传。