html5+js压缩图片上传

最近在折腾移动站的开发,涉及到了一个手机里面上传图片。于是经过N久的折腾,找到一个插件,用法如下:

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代码:

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,写入到一个文件去。

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

然后发现我朋友也写有一篇这个插件的使用的文章,地址在这里:http://a3147972.blog.51cto.com/2366547/1551066

上一篇:spring容器、BeanFactory、ApplicatContext、WebApplicationContext


下一篇:基于前台vue,后台是spring boot的压缩图片上传