星空网 > 软件开发 > 网页设计

html5 实现简单的上传

简单记录下今早做H5上传中一些代码还有坑

一、展示

因为前端上传文件是必须通过form表单的,不能使用ajax,这样的话一个移动页面放入一个type为file的input真心不怎么好看,如下图,很挫有没有

html5 实现简单的上传

解决办法找了下,PC上有些是把这个input换成flash,采用jquery的工具库比如uploadify来做,但是移动端大部分浏览器是不支持flash的。所以最后采用的办法还是用form表单的形式,只是把这个form和input的透明度设置为0,让它们和准备显示的内容同时在一个div中,显示的内容可以做成自己想要的样子。代码如下:

<!DOCTYPE html><html>  <head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">    <title></title>    <style>      div{width: 100%;}      .logo img{display:block; margin:0 auto;}      .upload{position: relative;width: 80px;height: 18px;line-height: 18px;background: #2fc7c9;text-align: center;          color: #FFF;padding: 0px 5px;-webkit-border-radius: 2px;border-radius: 2px;          margin: 0 auto;          }      .upload form{width:100%;position:absolute; left:0; top:0;opacity:0; filter:alpha(opacity=0);}      .upload form input{width: 100%;}    </style>  </head>  <body>    <div class="logo">      <img src='/images/loading.gif' data-original="img/1.jpg" />    </div>    <div class="upload">      <p>上传图片</p>      <form>        <input type="file" />      </form>    </div>  </body></html>

html5 实现简单的上传样子如左图,这样展现就在“上传图片”这个p标签中,点击它就有选择file的效果

 

二、JS代码

我这边写的蛮简单的,只是用了下h5上传的的基本功能

html代码如下,action为要请求的路径,我这边做的是当文件发生改变时就上传修改头像,input标签的name属性不能省去,具体跟后端接口有关

<form id="uploadForm" enctype="multipart/form-data" method="post" action="XXXXXX">   <input type="file" name="imageFile" id="imageFile" onchange="fileSelected()" /></form>

var iMaxFilesize = 2097152; //2Mwindow.fileSelected = function() {  var oFile = document.getElementById('imageFile').files[0];  //读取文件  var rFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;  if (!rFilter.test(oFile.type)) {    alert("文件格式必须为图片");    return;  }  if (oFile.size > iMaxFilesize) {    alert("图片大小不能超过2M");    return;  }  var vFD = new FormData(document.getElementById('uploadForm')),  //建立请求和数据    oXHR = new 'load', function(resUpload) {    //成功  }, false);  oXHR.addEventListener('error', function() {    //失败  }, false);  oXHR.addEventListener('abort', function() {    //上传中断  }, false);  oXHR.open('POST', actionUrl);  oXHR.send(vFD);};

 




原标题:html5 实现简单的上传

关键词:HTML

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

fba头程物流服务:https://www.goluckyvip.com/tag/20043.html
fba头程物流商:https://www.goluckyvip.com/tag/20045.html
fba头程系统:https://www.goluckyvip.com/tag/20046.html
fba头程需要多少钱:https://www.goluckyvip.com/tag/20047.html
fba头程要多少钱:https://www.goluckyvip.com/tag/20049.html
关键词分类:https://www.goluckyvip.com/tag/2005.html
恐怖游轮2002 恐怖游轮2022:https://www.vstour.cn/a/365178.html
时尚电商平台Meesho拟融资3亿美元!:https://www.kjdsnews.com/a/1836524.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流