js图片转换为Base64上传

前端js使用readAsDataURL.readAsDataURL()方法图片转换为Base64格式数据,代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Blob Test</title>
 6     <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
 7 </head>
 8 
 9 <body>
10 <table border="1" bordercolor="red">
11     <tr style="height: 300px;">
12         <td style="width: 20px;">
13             <div id="show"></div>
14         </td>
15     </tr>
16 </table>
17 <form id="myform" enctype="multipart/form-data" action="http://localhost:8072/hello/uploadBase64" method="post">
18     <input type="hidden" id="imgData" name="imgData">
19     <input type="file" id="file" name="file" onchange="showImg()">
20     <input type="submit" id="save" name="save" value="上传图片">
21 </form>
22 </body>
23 <script>
24     function showImg() {
25         var file = document.getElementById("file").files[0];
26         var reader = new FileReader();
27         reader.readAsDataURL(file);
28         reader.onload = function (e) {
29             var imgBase64Data = e.target.result;
30             console.info(imgBase64Data);
31             $("img").remove();
32             $("#show").append("<img src=\"" + imgBase64Data + "\"/>");
33             var head = imgBase64Data.indexOf("4") + 2;
34             imgBase64Data = imgBase64Data.substring(head, imgBase64Data.length - head);
35             console.info(imgBase64Data);
36             $("#imgData").attr("value", imgBase64Data);
37         }
38     }
39 </script>
40 </html>

后端使用spring mvc,代码:

 1     @RequestMapping(value = "/uploadBase64" , method = RequestMethod.POST)
 2     public void uploadBase64(HttpServletRequest req) throws Exception {
 3         String imgData=req.getParameter("imgData");
 4         byte[] byteImgData = null;
 5         BASE64Decoder base64Decoder = new BASE64Decoder();
 6         byteImgData = base64Decoder.decodeBuffer(imgData);
 7 
 8         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
 9         String path =  req.getSession().getServletContext().getRealPath("/")+
10                 "upload/"+sdf.format(new Date())+".jpg";
11         File newFile = new File(path);
12         OutputStream out = new FileOutputStream(newFile);
13         out.write(byteImgData);
14         out.flush();
15         out.close();
16         //TODO 返回页面
17     }

参考:

https://www.cnblogs.com/zzb-yp/p/9443534.html

https://blog.csdn.net/izb2008/article/details/79623234

猜你喜欢

转载自www.cnblogs.com/fxma/p/11733810.html