微信端上传图片方式1

1.H5的图片上传方式

前台代码:

 1 <form action="<%=basePath%>open/njResult.shtml"  id="njForm"  method="post">
 2      <input id="photoPath"  type="hidden" name="photoPath">
 3   </form>
 4         <div class="noUld_upB g-clear">
 5                 <div class="noUld_up">
 6                       <img class="noUld_up_img" data-up="img" src="<%=basePath %>resources/img/all/other_addImg.png">
 7                       <div class="noUld_up_cnt g-clear">
 8                           <div class="fl">请上传图片</div>
 9                           <div class="noUld_up_cnt_r"><span class="btn-s">上传</span><input type="file" id="notPassPhoto" data-up="file"></div>
10                      </div>
11                  </div>
12       
13         <div class="yesCek_submit">
14           <a id="njSumit" href="javascript:void(0)" class="btn-b">提交</a>
15         </div>

JS代码:

 1 //图片上传change事件
 2         $("#notPassPhoto ").change(function(){
 3             uploadBtnChange("notPassPhoto","photoPath");//上传图片改变时,调用base64压缩方法
 4             
 5         });
 6 $('#njSumit').click(function(){
 7     var photoPath = document.getElementById('photoPath').value;//获得压缩后的base64数据
 8 if(photoPath){
 9                     var ranparam = Math.random();
10                     $.ajax({
11                             url:"njNotPassPhoto.shtml",
12                             type: "POST",
13                             data:{'notPassphotoPath':photoPath,"ranparam":ranparam}, //把base64数据传到后台,由后台解码上传到服务器
14                             async : false,
15                         cache : false,
16                             success:function(data) {
17                                 if(data.status==200){
18                                     $("#photoPath").val(data.photoPath);//获得了传回来的图片路径,用于保存到数据库
19                                     $("#njForm").submit();//表单提交
20                                 }else{
21                                       alert(data.msg);
22                                   }
23                              },
24                             error: function(XMLHttpRequest, textStatus, errorThrown){  
25                                 alert(XMLHttpRequest.readyState + XMLHttpRequest.status + XMLHttpRequest.responseText); 
26                         }
27                           });
28                     }else{
29                                 alert("请上传照片")
30                                 return
31                             }
32             }
33                         
34         });
35  function uploadBtnChange(id,val){
36             var scope = this;
37             if(window.File && window.FileReader && window.FileList && window.Blob){ 
38                 // 获取上传file
39                 var filefield = document.getElementById(id),
40                     file = filefield.files[0];
41                 // 获取用于存放压缩后图片base64编码
42                 var compressValue = document.getElementById(val);
43                 processfile(file,compressValue);
44             }else{
45                 alert("此浏览器不完全支持压缩上传图片");
46             }
47         }
48 
49         function processfile(file,compressValue) {
50             var reader = new FileReader();
51             reader.onload = function (event) {
52                 var blob = new Blob([event.target.result]); 
53                 window.URL = window.URL || window.webkitURL;
54                 var blobURL = window.URL.createObjectURL(blob); 
55                 var image = new Image();
56                 image.src = blobURL;
57                 image.onload = function() {
58                     var resized = resizeMe(image); 
59                     compressValue.value = resized;
60                 }
61             };
62             reader.readAsArrayBuffer(file);
63         }
64 
65         function resizeMe(img) {
66             // 压缩的大小
67             var max_width = 800; 
68             var max_height = 600; 
69 
70             var canvas = document.createElement('canvas');
71             var width = img.width;
72             var height = img.height;
73             if(width > height) {
74                 if(width > max_width) {
75                     height = Math.round(height *= max_width / width);
76                     width = max_width;
77                 }
78             }else{
79                 if(height > max_height) {
80                     width = Math.round(width *= max_height / height);
81                     height = max_height;
82                 }
83             }
84 
85             canvas.width = width;
86             canvas.height = height;
87 
88             var ctx = canvas.getContext("2d");
89             ctx.drawImage(img, 0, 0, width, height);
90             // 压缩率
91             return canvas.toDataURL("image/jpeg",0.92); 
92         }     

后台代码:

 1 /**
 2      * Base64解码上传
 3      */
 4     @RequestMapping(value = "/njNotPassPhoto", method = RequestMethod.POST)
 5     @ResponseBody
 6     public Map<String, Object> njNotPassPhoto(String notPassphotoPath) {
 7         try {
 8             String photoPath = FileUploadUtils.getPath(notPassphotoPath);
 9             resultMap.put("status", 200);
10             resultMap.put("photoPath", photoPath);
11             return resultMap;
12         } catch (Exception e) {
13             e.printStackTrace();
14             resultMap.put("status", 500);
15             resultMap.put("msg", "服务器异常");
16         }
17         return null;
18 
19     }
FileUploadUtils工具类代码:
 1 public class FileUploadUtils {
 2     private static SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
 3 
 4     public static String getPath(String base64) throws IOException {
 5 
 6         String saveFileName = System.currentTimeMillis()
 7                 + RandomStringUtils.random(6, true, true) + ".jpg";
 8         Date date = new Date();
 9         String datePath = format.format(date);
10         String upload = "D:\\suyi\\photo\\" + datePath + "\\";
11 
12         String path = upload + saveFileName;
13         // base64图片解码
14         // 对字节数组字符串进行Base64解码并生成图片
15         if (base64 == null) // 图像数据为空
16             return "";
17         base64 = base64.replaceAll("data:image/jpeg;base64,", "");
18         BASE64Decoder decoder = new BASE64Decoder();
19         byte[] b = decoder.decodeBuffer(base64);
20         for (int i = 0; i < b.length; ++i) {
21             if (b[i] < 0) {// 调整异常数据
22                 b[i] += 256;
23             }
24         }
25 
26         File dir = new File(upload);
27         if (!dir.exists()) {
28             dir.mkdirs();
29         }
30         String fileName = path;
31         File file = new File(fileName);
32         OutputStream out = new FileOutputStream(file);
33         out.write(b);
34         out.flush();
35         out.close();
36         String ImagePath = "/suyi/showImage?imgId=" + datePath + "_"
37                 + saveFileName;
38         return ImagePath;
39 
40     }
41 }

 

 

 

posted @ 2018-01-11 12:55  生根  阅读(741)  评论(0编辑  收藏  举报