JS上传文件显示进度条
酷爱编程的小猿同学 人气:0用户反馈:图片上传过程中,如果网络比较慢,会发现上传图片后没有一点反应,体验性很差,图片回显也比较慢
解决思路:通过XMLHttpRequest的progress来实现监听图片上传的进度,实时显示百分比,后台保存图片成功后再将图片转为Base64编码的字符串在前端显示出来,这样可以很大程度提高用户体验
需要达到的效果:
1、用户可以看到图片上传进度条百分比
2、提升图片回显速度(将图片转为Base64编码的字符串在前端显示)
HTML代码:
<!-- 上传input --> <input class="file-input" name="uploadImage" id="uploadImage" type="file"> <!-- 上传进度条显示 --> <a id="showProgress" style="display:none;" href="#"></a>
JS代码:
// 上传input绑定一个change事件 $("#uploadImage").on("change", uploadPicture()); // 上传方法,里面处理进度条逻辑 function uploadPicture() { var $this= $(this); document.getElementById("showProgress").style.display="block"; var fd = new FormData(); fd.append("file", $this.context.files[0]); var xhr = new XMLHttpRequest(); //上传中设置上传的百分比 xhr.upload.addEventListener("progress", function(evt){ if (evt.lengthComputable) { var percentComplete = Math.round(evt.loaded * 100 / evt.total); if (percentComplete == 100){ setTimeout(function () { document.getElementById("showProgress").innerHTML = '已上传'+percentComplete+"%"; },1500) }else{ document.getElementById("showProgress").innerHTML = '已上传'+percentComplete+"%"; } }else { document.getElementById("showProgress").innerHTML = '无法计算'; } }, false); //请求完成后执行的操作 xhr.addEventListener("load", function(evt){ var message = evt.target.responseText, obj = eval("("+message+")"); $("#uploadImage").attr("src",obj); document.getElementById("showProgress").style.display="none"; alert("上传成功!"); }, false); //请求error xhr.addEventListener("error", uploadFailed, false); //请求中断 xhr.addEventListener("abort", uploadCanceled, false); //发送请求 xhr.open("POST", /uploadPicture.json); xhr.send(fd); } function uploadFailed(evt) { alert("上传出错."); } function uploadCanceled(evt) { alert("上传已由用户或浏览器取消删除连接."); }
后台代码:
/** * 上传图片 * @param request * @return */ @RequestMapping(value = "/uploadPicture", method = RequestMethod.POST) @ResponseBody public String uploadPicture(HttpServletRequest request) { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; Iterator<String> iter = multipartRequest.getFileNames(); MultipartFile file = null; while (iter.hasNext()) { file = multipartRequest.getFile(iter.next()); } CommonsMultipartFile cFile = (CommonsMultipartFile) file; DiskFileItem fileItem = (DiskFileItem) cFile.getFileItem(); String filePath = ""; byte[] data = null; String originalFilename = file.getOriginalFilename(); try { String fileType = originalFilename.substring( originalFilename.lastIndexOf(".") + 1).toLowerCase(); float bb = bytes2kb(file.getSize()); if (bb > 10) { throw new Exception("文件上传失败,最大上传大小为10M。"); } filePath = 上传图片方法,这里改为自己公司的; // 转为输入流 InputStream inputStream = fileItem.getInputStream(); data = new byte[inputStream.available()]; inputStream.read(data); inputStream.close(); // 对字节数组进行Base64编码,得到Base64编码的字符串 BASE64Encoder encoder = new BASE64Encoder(); String base64Str = encoder.encode(data); return "data:image/jpeg;base64,"+base64Str; } catch (Exception e) { e.printStackTrace(); } return null; } public static float bytes2kb(long bytes) { BigDecimal filesize = new BigDecimal(bytes); BigDecimal megabyte = new BigDecimal(1024 * 1024); float returnValue = filesize.divide(megabyte, 2, 0) .floatValue(); return returnValue; }
加载全部内容