html5+js壓縮圖片上傳

最近在折騰移動站的開發,涉及到了一個手機裏面上傳圖片。因而通過N久的折騰,找到一個插件,用法以下:javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<!DOCTYPE HTML>
< html lang = "zh-CN" >
< meta name = "viewport" content = "initial-scale=1.0, maximum-scale=1.0,user-scalable=no" /> 
< head >
     < meta charset = "UTF-8" >
     < title >LocalResizeIMG</ title >
</ head >
< style >
     body {
         margin: 20px 20%;
         color:#777;
         text-align: center;
     }
</ style >
< body >
     < h1 class = "text-center" >LocalResizeIMG-本地壓縮 1.0</ h1 >
     < hr />
     < input type = "file" />
     < hr />
 
     <!-- javascript
         ================================================== -->
     < script src = "/api/localResizeIMG-gh-pages/patch/jquery-2.1.1.min.js" type = "text/javascript" ></ script >
     < script src = "/api/localResizeIMG-gh-pages/LocalResizeIMG.js" type = "text/javascript" ></ script >
     
     <!-- mobileBUGFix.js 兼容修復移動設備 -->
     < script src = "/api/localResizeIMG-gh-pages/patch/mobileBUGFix.mini.js" type = "text/javascript" ></ script >
     < script type = "text/javascript" >
         $('input:file').localResizeIMG({
              width: 500,
              quality: 0.8,
              success: function (result) {
                  var img = new Image();
                  img.src = result.base64;
     
                  $('body').append(img);
                  //console.log(result);
                 $.ajax({
                      url: './uploads.php',
                      type: 'POST',
                      data:{formFile:result.clearBase64},
                      dataType: 'HTML',
                      timeout: 1000,
                      error: function(){
                          alert('Error loading PHP document');
                     },
                      success: function(result){
                          //console.log(result);
                         alert("Uploads success~")
                     }
                  });
              }
          });
     </ script >
</ body >
</ html >

PHP代碼:php

1
2
3
4
5
6
<?php
     $base64 = $_POST [ 'formFile' ];
     $IMG = base64_decode ( $base64 );
     $path = './' ;
     file_put_contents ( $path .time(). '.jpg' , $IMG );
?>

 

在前端把圖片壓縮,而後轉換成爲Base64的編碼,再把Base64的編碼使用AJAX來POST到服務器,而後在PHP解開Base64,寫入到一個文件去。html

原插件地址:http://github.com/think2011/LocalResizeIMG前端

而後發現我朋友也寫有一篇這個插件的使用的文章,地址在這裏:http://a3147972.blog.51cto.com/2366547/1551066java

相關文章
相關標籤/搜索