Web文件上传——Base64方式
前端:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>简单的html5 File测试 for pic2base64</title> <style> </style> <script> window.onload = function () { var input = document.getElementById("fielinput"); var txshow = document.getElementById("txshow"); if (typeof (FileReader) === 'undefined') { result.innerHTML = "抱歉,你的浏览器不支持 FileReader,请使用现代浏览器操作!"; input.setAttribute('disabled', 'disabled'); } else { input.addEventListener('change', readFile, false); txshow.onclick = function () { input.click(); } } } function readFile() { var file = this.files[0]; //判断是否是图片类型 /*if (!/image\/\w+/.test(file.type)) { alert("只能选择图片"); return false; }*/ var reader = new FileReader(); reader.readAsDataURL(file); reader.onload = function (e) { txshow.src = this.result; document.getElementById("data").innerText=this.result.substring(this.result.indexOf(',')+1); } } </script> </head> <body> <input type="file" id="fielinput" /> <img id="txshow" style="width:100px;height:100px;"/> <br/>解析之后的base64数据:<br/> <p id="data"></p> </body> </html>
后台:
//BASE64解码成File文件 public UapAttachs toolsBase64ToFile(String base64, String fileName) { UapAttachs uapAttachs = null; if ( base64 != null && !base64.isEmpty()) { String FILEPATH;//文件路径 String FILENAME;//文件名 String FILEEXT = "";//文件后缀 Long FILESIZE;//文件大小 String emcrypt;//加密后的文件名 // FILESIZE = (file.getSize()/1048576); FILESIZE = (base64.length()-(base64.length()/8L)*2L)/1048576; /*限制20MB大小以内*/ if (FILESIZE > 20) { return null; } /* 创建附件文件夹 */ emcrypt = String.valueOf(System.currentTimeMillis()); File attachment = new File("attachment"); if (!attachment.exists()) { attachment.mkdir(); } /* 创建本地文件 */ FILENAME = fileName!=null?fileName:""; if (FILENAME.indexOf(".") >= 0) { FILEEXT = FILENAME.substring(FILENAME.lastIndexOf(".")+1,FILENAME.length()); } File targetfile = new File(attachment.getAbsolutePath(),emcrypt+"_"+FILENAME); /* 解码base64到文件对象 */ BufferedOutputStream bos = null; java.io.FileOutputStream fos = null; try { byte[] bytes = Base64.getDecoder().decode(base64); fos = new java.io.FileOutputStream(targetfile); bos = new BufferedOutputStream(fos); bos.write(bytes); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } /* 返回文件对象信息 */ FILEPATH = targetfile.getPath().replace("\\", "/"); uapAttachs = new UapAttachs(); if (targetfile.exists()) { uapAttachs.setFilepath(FILEPATH); uapAttachs.setFilename(FILENAME); uapAttachs.setFileext(FILEEXT); uapAttachs.setFilesize(FILESIZE); uapAttachs.setAttachtype(""); uapAttachs.setCnname(""); uapAttachs.setObjvalue(""); uapAttachs.setObjid(3529L); } } return uapAttachs; }