layui实现页面粘贴图片直接Ajax上传实例页面
时间: 2023-09-18 10:10:16 浏览: 58
以下是一个使用 layui 实现页面粘贴图片直接 Ajax 上传的示例页面:
HTML 代码:
```html
<div class="layui-upload">
<button type="button" class="layui-btn" id="upload">上传图片</button>
<div class="layui-upload-list">
<img class="layui-upload-img" id="image">
<p id="text"></p>
</div>
</div>
```
JavaScript 代码:
```javascript
layui.use(['upload', 'layer'], function(){
var $ = layui.jquery,
upload = layui.upload,
layer = layui.layer;
// 图片上传
upload.render({
elem: '#upload',
acceptMime: 'image/*',
exts: 'jpg|png|gif|bmp|jpeg',
size: 1024 * 10,
done: function(res){
if (res.code == 0) {
$('#image').attr('src', res.data.src);
$('#text').text('上传成功');
} else {
layer.msg(res.msg, {icon: 2});
}
},
error: function(){
layer.msg('上传失败', {icon: 2});
}
});
// 监听粘贴事件
document.addEventListener('paste', function(e){
var items = e.clipboardData && e.clipboardData.items;
var file = null;
if (items && items.length) {
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
file = items[i].getAsFile();
break;
}
}
}
if (file !== null) {
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(res){
if (res.code == 0) {
$('#image').attr('src', res.data.src);
$('#text').text('上传成功');
} else {
layer.msg(res.msg, {icon: 2});
}
},
error: function(){
layer.msg('上传失败', {icon: 2});
}
});
}
});
});
```
说明:
1. 使用 layui 的 upload 模块实现图片上传功能。
2. 监听粘贴事件,在粘贴图片时将图片转为 FormData 对象并通过 Ajax 上传到服务器。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)