关键词:
做移动端开发的时候,form里面的file后台经常获取不到,用foemdata也拿不到
找到了一个formdata的脚本
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"> <title>移动端图片压缩上传demo</title> <style> *{margin: 0;padding: 0;} li{list-style-type: none;} a,input{outline: none;-webkit-tap-highlight-color:rgba(0,0,0,0);} #choose{display: none;} canvas{width: 100%;border: 1px solid #000000;} #upload{display: block;margin: 10px;height: 60px;text-align: center;line-height: 60px;border: 1px solid;border-radius: 5px;cursor: pointer;} .touch{background-color: #ddd;} .img-list{margin: 10px 5px;} .img-list li{position: relative;display: inline-block;width: 100px;height: 100px;margin: 5px 5px 20px 5px;border: 1px solid rgb(100,149,198);background: #fff no-repeat center;background-size: cover;} .progress{position: absolute;width: 100%;height: 20px;line-height: 20px;bottom: 0;left: 0;background-color:rgba(100,149,198,.5);} .progress span{display: block;width: 0;height: 100%;background-color:rgb(100,149,198);text-align: center;color: #FFF;font-size: 13px;} .size{position: absolute;width: 100%;height: 15px;line-height: 15px;bottom: -18px;text-align: center;font-size: 13px;color: #666;} .tips{display: block;text-align:center;font-size: 13px;margin: 10px;color: #999;} .pic-list{margin: 10px;line-height: 18px;font-size: 13px;} .pic-list a{display: block;margin: 10px 0;} .pic-list a img{vertical-align: middle;max-width: 30px;max-height: 30px;margin: -4px 0 0 10px;} </style> </head> <body> <input type="file" id="choose" accept="image/*" multiple> <ul class="img-list"></ul> <a id="upload">上传图片</a> <span class="tips">只允许上传jpg、png及gif</span> <div class="pic-list"> 你上传的图片(图片有效期为1分钟): </div> <script src="/public/jquery-2.1.1.min.js"></script> <script> var filechooser = document.getElementById("choose"); // 用于压缩图片的canvas var canvas = document.createElement("canvas"); var ctx = canvas.getContext(‘2d‘); // 瓦片canvas var tCanvas = document.createElement("canvas"); var tctx = tCanvas.getContext("2d"); var maxsize = 100 * 1024; $("#upload").on("click", function() { filechooser.click(); }) .on("touchstart", function() { $(this).addClass("touch") }) .on("touchend", function() { $(this).removeClass("touch") }); filechooser.onchange = function() { if (!this.files.length) return; var files = Array.prototype.slice.call(this.files); if (files.length > 9) { alert("最多同时只可上传9张图片"); return; } files.forEach(function(file, i) { if (!//(?:jpeg|png|gif)/i.test(file.type)) return; var reader = new FileReader(); var li = document.createElement("li"); // 获取图片大小 var size = file.size / 1024 > 1024 ? (~~(10 * file.size / 1024 / 1024)) / 10 + "MB" : ~~(file.size / 1024) + "KB"; li.innerHTML = ‘<div class="progress"><span></span></div><div class="size">‘ + size + ‘</div>‘; $(".img-list").append($(li)); reader.onload = function() { var result = this.result; var img = new Image(); img.src = result; $(li).css("background-image", "url(" + result + ")"); //如果图片大小小于100kb,则直接上传 if (result.length <= maxsize) { img = null; upload(result, file.type, $(li)); return; } // 图片加载完毕之后进行压缩,然后上传 if (img.complete) { callback(); } else { img.onload = callback; } function callback() { var data = compress(img); upload(data, file.type, $(li)); img = null; } }; reader.readAsDataURL(file); }) }; // 使用canvas对大图片进行压缩 function compress(img) { var initSize = img.src.length; var width = img.width; var height = img.height; //如果图片大于四百万像素,计算压缩比并将大小压至400万以下 var ratio; if ((ratio = width * height / 4000000) > 1) { ratio = Math.sqrt(ratio); width /= ratio; height /= ratio; } else { ratio = 1; } canvas.width = width; canvas.height = height; // 铺底色 ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height); //如果图片像素大于100万则使用瓦片绘制 var count; if ((count = width * height / 1000000) > 1) { count = ~~(Math.sqrt(count) + 1); //计算要分成多少块瓦片 // 计算每块瓦片的宽和高 var nw = ~~(width / count); var nh = ~~(height / count); tCanvas.width = nw; tCanvas.height = nh; for (var i = 0; i < count; i++) { for (var j = 0; j < count; j++) { tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh); ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh); } } } else { ctx.drawImage(img, 0, 0, width, height); } //进行最小压缩 var ndata = canvas.toDataURL(‘image/jpeg‘, 0.1); console.log(‘压缩前:‘ + initSize); console.log(‘压缩后:‘ + ndata.length); console.log(‘压缩率:‘ + ~~(100 * (initSize - ndata.length) / initSize) + "%"); tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0; return ndata; } // 图片上传,将base64的图片转成二进制对象,塞进formdata上传 function upload(basestr, type, $li) { var text = window.atob(basestr.split(",")[1]); var buffer = new Uint8Array(text.length); var pecent = 0, loop = null; for (var i = 0; i < text.length; i++) { buffer[i] = text.charCodeAt(i); } var blob = getBlob([buffer], type); var xhr = new XMLHttpRequest(); var formdata = getFormData(); formdata.append(‘imagefile‘, blob); xhr.open(‘post‘, ‘/cupload‘); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { var jsonData = JSON.parse(xhr.responseText); var imagedata = jsonData[0] || {}; var text = imagedata.path ? ‘上传成功‘ : ‘上传失败‘; console.log(text + ‘:‘ + imagedata.path); clearInterval(loop); //当收到该消息时上传完毕 $li.find(".progress span").animate({‘width‘: "100%"}, pecent < 95 ? 200 : 0, function() { $(this).html(text); }); if (!imagedata.path) return; $(".pic-list").append(‘<a href="‘ + imagedata.path + ‘">‘ + imagedata.name + ‘(‘ + imagedata.size + ‘)<img src="‘ + imagedata.path + ‘" /></a>‘); } }; //数据发送进度,前50%展示该进度 xhr.upload.addEventListener(‘progress‘, function(e) { if (loop) return; pecent = ~~(100 * e.loaded / e.total) / 2; $li.find(".progress span").css(‘width‘, pecent + "%"); if (pecent == 50) { mockProgress(); } }, false); //数据后50%用模拟进度 function mockProgress() { if (loop) return; loop = setInterval(function() { pecent++; $li.find(".progress span").css(‘width‘, pecent + "%"); if (pecent == 99) { clearInterval(loop); } }, 100) } xhr.send(formdata); } /** * 获取blob对象的兼容性写法 * @param buffer * @param format * @returns {*} */ function getBlob(buffer, format) { try { return new Blob(buffer, {type: format}); } catch (e) { var bb = new (window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder); buffer.forEach(function(buf) { bb.append(buf); }); return bb.getBlob(format); } } /** * 获取formdata */ function getFormData() { var isNeedShim = ~navigator.userAgent.indexOf(‘Android‘) && ~navigator.vendor.indexOf(‘Google‘) && !~navigator.userAgent.indexOf(‘Chrome‘) && navigator.userAgent.match(/AppleWebKit/(d+)/).pop() <= 534; return isNeedShim ? new FormDataShim() : new FormData() } /** * formdata 补丁, 给不支持formdata上传blob的android机打补丁 * @constructor */ function FormDataShim() { console.warn(‘using formdata shim‘); var o = this, parts = [], boundary = Array(21).join(‘-‘) + (+new Date() * (1e16 * Math.random())).toString(36), oldSend = XMLHttpRequest.prototype.send; this.append = function(name, value, filename) { parts.push(‘--‘ + boundary + ‘ Content-Disposition: form-data; name="‘ + name + ‘"‘); if (value instanceof Blob) { parts.push(‘; filename="‘ + (filename || ‘blob‘) + ‘" Content-Type: ‘ + value.type + ‘ ‘); parts.push(value); } else { parts.push(‘ ‘ + value); } parts.push(‘ ‘); }; // Override XHR send() XMLHttpRequest.prototype.send = function(val) { var fr, data, oXHR = this; if (val === o) { // Append the final boundary string parts.push(‘--‘ + boundary + ‘-- ‘); // Create the blob data = getBlob(parts); // Set up and read the blob into an array to be sent fr = new FileReader(); fr.onload = function() { oldSend.call(oXHR, fr.result); }; fr.onerror = function(err) { throw err; }; fr.readAsArrayBuffer(data); // Set the multipart content type and boudary this.setRequestHeader(‘Content-Type‘, ‘multipart/form-data; boundary=‘ + boundary); XMLHttpRequest.prototype.send = oldSend; } else { oldSend.call(this, val); } }; } </script> </body> </html>
在移动 Chrome 上上传图片表单失败
】在移动Chrome上上传图片表单失败【英文标题】:UploadPictureFormFailsOnMobileChrome【发布时间】:2014-12-3122:36:32【问题描述】:我正在构建一个移动网络应用程序,其中用户手机中的图片发挥了重要作用。我有这个表单,用户可以在... 查看详情
图片移动端图片上传旋转压缩的解决方案
移动端图片上传旋转、压缩的解决方案来源知乎 作者 林鑫 工作上有手机上传准考证等图片的功能,这个是非常必要的,作者写的很全面,就直接记录这个地址了 还有一篇文件的上传、下载 查看详情
移动端图片上传预览
前天要做wap版的图片上传预览,找了好半天才找到比较适合的插件,我在该插件的基础上修改了一些东西,比如:上传后的图片删除后不能再添加、不能限制上传图片的数量。input虽然有multiple(多选),但是android目前是不支持... 查看详情
移动端图片压缩上传解决方案
最近做移动端图片上传,发现图片尤其是iPhone拍照的图片都有2M左右,但是实际上项目中用不到这么大,于是想到要用js在前台进行压缩。解决方案如下: 【一】获取图片数据 先是获取图片数据,也就是监听inputfile的change... 查看详情
移动端h5实现拍照上传图片并预览
.移动端实现图片上传并预览,用到h5的input的file属性及filereader对象;经测除了android上不支持多图片上传,其他基本ok实用;一:先说一下单张图片上传(先上代码):html结构(含多张图片容器div):1<divclass="fileBtn">2<p>点... 查看详情
angularjs+ionic移动端图片上传的解决办法
...己写一个图片上传的方法。今天的demo是帮朋友做的一个移动端微信公众号项目,项目架构采用angular+ionic,因为对dom的操作jQuery会方便很多,但是j 查看详情
纯原生js移动端图片压缩上传插件
...就不吐槽了,然后当然是自己做了,先上图:纯原生js的移动端图片压缩上传插件,不依赖任何库用法在html页面中引入input标签,通过 查看详情
移动端调用相机拍照上传图片
<inputtype="file"capture="camera"accept="image/*"id="filetest"name="filetest">看这代码,重要的是capture="camera"accept="image/*"。 查看详情
移动端h5如何上传zip文件
参考技术A移动端h5上传zip文件方法:1、拍照或者选择图片并获取图片的路径。2、压缩图片。3、找到压缩完的图片先转换成base64再转换成可以添加到FormData上传的File。4、添加数据上传。 查看详情
vue移动端图片上传,可最多上传9张,使用webuploader插件
参考技术A图片上传WebUploader.js 查看详情
h5移动端实现图片文件上传(代码片段)
PC端上传文件多半用插件,引入flash都没关系,但是移动端要是还用各种冗余的插件估计得被喷死,项目里面需要做图片上传的功能,既然H5已经有相关的接口且兼容性良好,当然优先考虑用H5来实现。 JS代码:<scripttype="text... 查看详情
优化篇-“移动端”图片上传架构的变迁
...察,APP、WAP的用户量基本与PC端持平甚至超越,因此,应移动端用户体验和访问速度都被运营方盯得紧紧。在2014年的时候已经看到 查看详情
picker-extend移动端级联选择插件
...h1align="center">picker-extend.js</h1>一款多功能的移动端滚动选择器,支持单选到多选、支持多级级联、提供自定义回调函数、提供update函数二次渲染、重定位函数、兼容pc端拖拽等等..picker-extend移动端级联选择插件()p... 查看详情
移动端上传照片
...件,在这里我要感谢作者,虽然不知道是谁。应用场景:移动端管调用手机相册和相机,上传图片给接口进行识别插件下载百度云地址:链接:https:// 查看详情
移动端js实现图片上传预览
方法一:<htmlxmlns="http://www.w3.org/1999/xhtml"><head><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><title>测试页面</title><scripttype="text/javascript"&g 查看详情
移动端图片上传旋转压缩的解决方案
在手机上通过网页input标签拍照上传图片,有一些手机会出现图片旋转了90度d的问题,包括iPhone和个别三星手机。这些手机竖着拍的时候才会出现这种问题,横拍出来的照片就正常显示。因此,可以通过获取手机拍照角度来对照... 查看详情
前端仿移动端时间插件,百度上传图片插件,监听滚动插入内容(代码片段)
仿移动端时间:https://docs.mobiscroll.com/jquery/eventcalendar#usage 结构:<inputid="scroller"/> 百度上传图片插件http://fex.baidu.com/webuploader/download.html监听滚动,可用来插入内容https://iiunknown.g 查看详情
移动端预览(双指缩放移动)富文本编辑器上传的图片(代码片段)
通过使用vue-photo-preview插件,实现移动端图片的预览,全屏等功能。1.安装插件npminstallvue-photo-preview--save2.main引入importpreviewfrom'vue-photo-preview'import'vue-photo-preview/dist/skin.css'Vue.use 查看详情