纯js实现图片上传预览功能
1、html
<div id="zTu">图片</div>
2、js上传方法封装
1 /** 2 * @description 上传图片 3 * @param {object} picker 4 * @param {string} url 5 * @param {function} callback 6 */ 7 function uploadImages(picker, url, callback) { 8 var img_uploader = WebUploader.create({ 9 auto: true, 10 server: url, 11 pick: picker, 12 fileNumLimit: 1, 13 fileSingleSizeLimit: 2097152, // 2M 14 accept: { 15 title: 'Images', 16 extensions: 'gif,jpg,jpeg,bmp,png', 17 // mimeTypes: 'image/*' 18 }, 19 compress: { 20 width: 300, 21 compressSize: 102400 // < 100kb 不压缩 22 }, 23 }) 24 25 var fileType = ['image/jpeg', 'image/jpg', 'image/gif', 'image/png', 'image/bmp'] 26 27 img_uploader.on('beforeFileQueued', function(file) { 28 29 fileType.some(function(name) { 30 return file.type === name 31 }) ? '' : alert('请上传正确的图片!') 32 33 }) 34 35 img_uploader.on('uploadSuccess', function(file, res) { 36 callback(file, res) 37 }) 38 39 img_uploader.on('uploadError', function(file, reason) { 40 console.log(reason); 41 }) 42 43 img_uploader.on('uploadComplete', function(file) { 44 img_uploader.reset() 45 }) 46 47 }
3、上传并预览
1 /** 2 * @description 手动上传并预览 3 */ 4 function initImageUploader(){ 5 var fileUrl = 你想上传的地址; 6 uploadImages('#imagePicker', fileUrl, function(file, res) { 7 var coverImage = res.url 8 $('#zTu').get(0).innerHTML = '<div class="file-item thumbnail"><img style="max-height:180px" src="' + res.url + '" /></div>' 9 }) 10 } 11 12 // 方法调用 13 initImageUploader();
<完>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!