标题: [精]【网页插件】网页粘贴图片(修改js为阿里云),无需上传文件至服务器
时间: 2021-06-29发布,2022-06-17修改
<script src="https://hu60.org/toastui-editor/spark-md5.min.js"></script>
<script src="http://file.hu60.cn/file/hash/js/983c474dc7ba81318d0e030cfda482456052.js?attname=file-hash-js-983c474dc7ba81318d0e030cfda482456052.js"></script>
<script src="http://file.hu60.cn/file/hash/js/130b1799c0b90d26bf160db9db2be9b63520.js?attname=base64.js"></script>
<script>
document.addEventListener('paste', function (event) {
console.log(event)
var isChrome = false;
if ( event.clipboardData || event.originalEvent ) {
//not for ie11 某些chrome版本使用的是event.originalEvent
var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
if ( clipboardData.items ) {
// for chrome
var items = clipboardData.items,
len = items.length,
blob = null;
isChrome = true;
//items.length比较有意思,初步判断是根据mime类型来的,即有几种mime类型,长度就是几(待验证)
//如果粘贴纯文本,那么len=1,如果粘贴网页图片,len=2, items[0].type = 'text/plain', items[1].type = 'image/*'
//如果使用截图工具粘贴图片,len=1, items[0].type = 'image/png'
//如果粘贴纯文本+HTML,len=2, items[0].type = 'text/plain', items[1].type = 'text/html'
// console.log('len:' + len);
// console.log(items[0]);
// console.log(items[1]);
// console.log( 'items[0] kind:', items[0].kind );
// console.log( 'items[0] MIME type:', items[0].type );
// console.log( 'items[1] kind:', items[1].kind );
// console.log( 'items[1] MIME type:', items[1].type );
//阻止默认行为即不让剪贴板内容在div中显示出来
//event.preventDefault();
//在items里找粘贴的image,据上面分析,需要循环
for (var i = 0; i < len; i++) {
if (items[i].type.indexOf("image") !== -1) {
// console.log(items[i]);
// console.log( typeof (items[i]));
//getAsFile() 此方法只是living standard firefox ie11 并不支持
blob = items[i].getAsFile();
}
}
if ( blob !== null ) {
var reader = new FileReader();
reader.onload = function (event) {
// event.target.result 即为图片的Base64编码字符串
var base64_str = event.target.result
//可以在这里写上传逻辑 直接将base64编码的字符串上传(可以尝试传入blob对象,看看后台程序能否解析)
uploadImgFromPaste(base64_str, 'paste', isChrome);
}
reader.readAsDataURL(blob);
}
} else {
//for firefox
setTimeout(function () {
//设置setTimeout的原因是为了保证图片先插入到div里,然后去获取值
var imgList = document.querySelectorAll('#tar_box img'),
len = imgList.length,
src_str = '',
i;
for ( i = 0; i < len; i ++ ) {
if ( imgList[i].className !== 'my_img' ) {
//如果是截图那么src_str就是base64 如果是复制的其他网页图片那么src_str就是此图片在别人服务器的地址
src_str = imgList[i].src;
}
}
uploadImgFromPaste(src_str, 'paste', isChrome);
}, 1);
}
} else {
//for ie11
setTimeout(function () {
var imgList = document.querySelectorAll('#tar_box img'),
len = imgList.length,
src_str = '',
i;
for ( i = 0; i < len; i ++ ) {
if ( imgList[i].className !== 'my_img' ) {
src_str = imgList[i].src;
}
}
uploadImgFromPaste(src_str, 'paste', isChrome);
}, 1);
}
})
function uploadImgFromPaste (file, type, isChrome) {
var formData = new FormData();
var ele = document.getElementById("content");
ele.value = ele.value + "《图片:"+ file +",图片》";
}
</script>
『回复列表(12|显示机器人聊天)』
// 引入 MD5 计算组件 https://hu60.org/toastui-editor/spark-md5.min.js
fileUpload(blob, (url) => alert('上传成功:' + url));
function fileUpload(blob, callback) {
let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
file = blob,
chunkSize = 2097152, // Read in chunks of 2MB
chunks = Math.ceil(file.size / chunkSize),
currentChunk = 0,
spark = new SparkMD5.ArrayBuffer(),
fileReader = new FileReader();
fileReader.onload = function (e) {
spark.append(e.target.result);
currentChunk++;
if (currentChunk < chunks) {
loadNext();
} else {
console.debug('完成hash计算');
let fileMd5Hash = spark.end();
console.debug(fileMd5Hash);
fetch("/q.php/api.qiniu.json", {
method: 'GET'
,credentials: 'same-origin'
,headers: {
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(response => response.json())
.then(function (qiniu) {
console.debug('获取七牛云上传Token成功', qiniu);
let fileExt = blob.name.split('.').pop();
let formData = new FormData();
formData.append('file', blob);
formData.append('key', 'file-hash-' + fileExt + '-' + fileMd5Hash + blob.size + '.' + fileExt);
formData.append('token', qiniu.uptoken);
formData.append('name', blob.name);
console.debug('上传文件到七牛云');
fetch('https://' + qiniu.zone.cdnUpHosts[0], {
body: formData
,method: 'POST'
,credentials: 'same-origin'
,headers: {
'X-Requested-With': 'XMLHttpRequest'
}
})
.then(response => response.json())
.then(function (result) {
console.debug('文件上传成功', result)
callback('http://' + qiniu.host + '/' + result.key);
})
.catch(function (error) {
console.warn(error);
alert('上传失败:' + error);
});
})
.catch(function (error) {
console.warn(error);
alert('获取七牛云上传Token失败:' + error);
});
}
};
fileReader.onerror = function () {
console.warn('oops, something went wrong.');
};
function loadNext() {
var start = currentChunk * chunkSize,
end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
}
loadNext();
}