jQuery插件jcrop+Fileapi完美实现图片上传+裁剪+预览的代码分享


Posted in Javascript onApril 22, 2015

网页端 裁剪图片,不需要经过服务器。

这个是用 https://github.com/mailru/FileAPI 框架实现的。配合jcrop.

高级浏览器 使用 canvas 裁剪,ie6 7 8使用 flash过度。

核心代码:

var el = $('input').get(0);
     
     seajs.use(['gallery/jcrop/0.9.12/jcrop.css','gallery/jcrop/0.9.12/jcrop.js'] ,function(){
     
    FileAPI.event.on(el, 'change', function (evt){
      var files = FileAPI.getFiles(evt); // Retrieve file list
 
      FileAPI.filterFiles(files, function (file, info){
        if( !/^image/.test(file.type)  ){
          alert('图片格式不正确');
          return false;
        }
        else if(file.size > 20 * FileAPI.MB){
          alert('图片必须小于20M');
           return false;
        }
        else{
          return true;
        }
        
      }, function (files, rejected){
        console.log(files);
         
        if( files.length ){
          var file = files[0];
           var img0 = FileAPI.Image(file);
           var img1 = FileAPI.Image(file);
           var ratio = 0;
          FileAPI.getInfo(file, function (err, info) {  //get image ratio
              if (!err) {
                if (info.width > info.height) {
                  ratio = info.width / 500;
                }
                else {
                  ratio = info.height / 500;
                }
              }
            });
 
            img0.resize(500, 500, 'max')   //place image and register jcrop
                .get(function(err, img) {
                  $('#img2').empty();
                  $('#img2').append($(img));
 
                  $('#img2').children().Jcrop({
                    aspectRatio: 1,
                    bgColor: 'rgba(0,0,0,0.4)',
                    onSelect: function(c) {
                      img1.matrix.sx = c.x * ratio;
                      img1.matrix.sy = c.y * ratio;
                      img1.matrix.sw = c.w * ratio;
                      img1.matrix.sh = c.h * ratio;
                      img1.matrix.dw = 500;
                      img1.matrix.dh = 500;
 
                      img1.get(function(err, img) {
                        // $('#img3').empty();
                        //   $('#img3').append($(img));
                        $('#img3').html($(img));
                      });
 
                    }
                  });
                });
                  $('#btn').on('click',function(){
                        FileAPI.upload({
//                          url: '/testUpFile/upFile',
                          // headers: { 'Content-Type': 'multipart/form-data' },
                          files: { images: img1 },
                          progress: function (evt){ /* ... */ },
                          complete: function (err, xhr){ /* ... */
                            //alert(xhr.responseText);
                            console.log(xhr);
                          }
                        });              
                  });
          }
        });
      });
  });

完整代码:

<!DOCTYPE html>
<html>
  <head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">
    <script src="./jquery.min.js"></script>  
    <script src="./jcrop/jquery.Jcrop.min.js"></script>
    <link href="./jcrop/jquery.Jcrop.min.css" rel="stylesheet">
  </head>
  <style>
    
    .upload-btn {
  width: 130px;
  height: 25px;
  overflow: hidden;
  position: relative;
  border: 3px solid #06c;
  border-radius: 5px;
  background: #0cf;

}
  .upload-btn:hover {
    background: #09f;
  }
  .upload-btn__txt {
    z-index: 1;
    position: relative;
    color: #fff;
    font-size: 18px;
    font-family: "Helvetica Neue";
    line-height: 24px;
    text-align: center;
    text-shadow: 0 1px 1px #000;
  }
  .upload-btn input {
    top: -10px;
    right: -40px;
    z-index: 2;
    position: absolute;
    cursor: pointer;
    opacity: 0;
    filter: alpha(opacity=0);
    font-size: 50px;
  }
    
  </style>
 
  
  <body>
    <div>
    <!-- "js-fileapi-wrapper" -- required class -->
    <div class="js-fileapi-wrapper upload-btn" id="choose">
       
      <input name="files" type="file" multiple />
      <button id="btn">上传</button>
    </div>
    <div id="images">
 
      <p style="margin-top: 40px;"></p>
      
      <div id="img2" ></div>
      
      <div id="img3"></div>
    </div>

  </div>

  <script>window.FileAPI = { staticPath: './fileapi/' };</script>
  <script src="./fileapi/FileAPI.min.js"></script>
  <script>
 
    var el = $('input').get(0);
    
 
    FileAPI.event.on(el, 'change', function (evt){
      var files = FileAPI.getFiles(evt); // Retrieve file list

      FileAPI.filterFiles(files, function (file, info){
        if( !/^image/.test(file.type)  ){
          alert('图片格式不正确');
          return false;
        }
        else if(file.size > 20 * FileAPI.MB){
          alert('图片必须小于20M');
           return false;
        }
        else{
          return true;
        }
        
      }, function (files, rejected){
 
        
        if( files.length ){
          var file = files[0];
           var img0 = FileAPI.Image(file);
           var img1 = FileAPI.Image(file);
           var ratio = 0;
          FileAPI.getInfo(file, function (err, info) {  //get image ratio
              if (!err) {
                if (info.width > info.height) {
                  ratio = info.width / 500;
                }
                else {
                  ratio = info.height / 500;
                }
              }
            });

            img0.resize(500, 500, 'max')   //place image and register jcrop
                .get(function(err, img) {
                  $('#img2').empty();
                  $('#img2').append($(img));

                  $('#img2').children().Jcrop({
                    aspectRatio: 1,
                    bgColor: 'rgba(0,0,0,0.4)',
                    onSelect: function(c) {
                      img1.matrix.sx = c.x * ratio;
                      img1.matrix.sy = c.y * ratio;
                      img1.matrix.sw = c.w * ratio;
                      img1.matrix.sh = c.h * ratio;
                      img1.matrix.dw = 500;
                      img1.matrix.dh = 500;

                      img1.get(function(err, img) {
                        // $('#img3').empty();
                        //   $('#img3').append($(img));
                        $('#img3').html($(img));
                      });

                    }
                  });
                });
                  $('#btn').on('click',function(){
                        FileAPI.upload({
                        url: '/testUpFile/upFile',
 
                          files: { images: img1 },
                          progress: function (evt){ /* ... */ },
                          complete: function (err, xhr){ /* ... */
                            //alert(xhr.responseText);
 
                          }
                        });
                    
                  });

          }
        });
      });
  
  </script>
  </body>
</html>

以上所述就是本文的全部内容了,希望大家能够喜欢。

Javascript 相关文章推荐
javascript 冒号 使用说明
Jun 06 Javascript
jquery数组之存放checkbox全选值示例代码
Dec 20 Javascript
ECMAScript6的新特性箭头函数(Arrow Function)详细介绍
Jun 07 Javascript
详解Javascript模板引擎mustache.js
Jan 20 Javascript
JavaScript中的Array 对象(数组对象)
Jun 02 Javascript
JavaScript_ECMA5数组新特性详解
Jun 12 Javascript
JavaScript如何实现跨域请求
Aug 05 Javascript
jQuery正则验证注册页面经典实例
Jun 10 jQuery
关于vue-resource报错450的解决方案
Jul 24 Javascript
基于vue开发的在线付费课程应用过程
Jan 25 Javascript
微信小程序全局变量功能与用法详解
Jan 22 Javascript
JavaScript函数柯里化实现原理及过程
Dec 02 Javascript
javascript解三阶幻方(九宫格)
Apr 22 #Javascript
javascript递归回溯法解八皇后问题
Apr 22 #Javascript
使用C++为node.js写扩展模块
Apr 22 #Javascript
node.js 使用ejs模板引擎时后缀换成.html
Apr 22 #Javascript
JavaScript模拟深蓝vs卡斯帕罗夫的国际象棋对局示例
Apr 22 #Javascript
jscript读写二进制文件的方法
Apr 22 #Javascript
javascript格式化json显示实例分析
Apr 21 #Javascript
You might like
laravel执行php artisan migrate报错的解决方法
2019/10/09 PHP
phpmyadmin在宝塔面板里进不去的解决方案
2020/07/06 PHP
javascript背投广告代码的完善
2008/04/08 Javascript
基于jquery的web页面日期格式化插件
2011/11/15 Javascript
用js的document.write输出的广告无阻塞加载的方法
2014/06/05 Javascript
详解JavaScript的Polymer框架中的通知交互
2015/07/29 Javascript
jQuery插件Validate实现自定义表单验证
2016/01/18 Javascript
JS模拟简易滚动条效果代码(附demo源码)
2016/04/05 Javascript
微信JS-SDK坐标位置如何转换为百度地图坐标
2016/07/04 Javascript
一个极为简单的requirejs实现方法
2016/10/20 Javascript
JavaScript中Array对象用法实例总结
2016/11/29 Javascript
jQuery上传多张图片带进度条样式(DEMO)
2017/03/02 Javascript
windows系统下更新nodejs版本的方案
2017/11/24 NodeJs
详解Angular Karma测试的持续集成实践
2019/11/15 Javascript
linux服务器快速卸载安装node环境(简单上手)
2021/02/22 Javascript
[14:51]DOTA2 HEROS教学视频教你分分钟做大人-卓尔游侠
2014/06/13 DOTA
Python二分法搜索算法实例分析
2015/05/11 Python
Python实现LRU算法的2种方法
2015/06/24 Python
windows系统下Python环境的搭建(Aptana Studio)
2017/03/06 Python
python多行字符串拼接使用小括号的方法
2020/03/19 Python
详解Django模版中加载静态文件配置方法
2019/07/21 Python
python 修改本地网络配置的方法
2019/08/14 Python
python3多线程知识点总结
2019/09/26 Python
python3的UnicodeDecodeError解决方法
2019/12/20 Python
PyTorch的torch.cat用法
2020/06/28 Python
Django model class Meta原理解析
2020/11/14 Python
New Balance美国官网:运动鞋和健身服装
2017/04/11 全球购物
Skyscanner波兰:廉价航班
2017/11/07 全球购物
什么造成了Java里面的异常
2016/04/24 面试题
多媒体编辑专业毕业生推荐信
2013/11/05 职场文书
剪枝的学问教学反思
2014/02/07 职场文书
网管求职信
2014/03/03 职场文书
对外汉语专业大学生职业生涯规划范文
2014/09/13 职场文书
我的长征观后感
2015/06/09 职场文书
九年级数学教学反思
2016/02/17 职场文书
mysql通过group by分组取最大时间对应数据的两种有效方法
2022/09/23 MySQL