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 相关文章推荐
客户端脚本中常常出现的一些问题和调试技巧
Jan 09 Javascript
对setInterval在火狐和chrome切换标签产生奇怪的效果之探索,与解决方案!
Oct 29 Javascript
JS判定是否原生方法
Jul 22 Javascript
我的Node.js学习之路(二)NPM模块管理
Jul 06 Javascript
AngularJS初始化过程分析(引导程序)
Dec 06 Javascript
node.js中的fs.writeFile方法使用说明
Dec 14 Javascript
node.js中的fs.lchmodSync方法使用说明
Dec 16 Javascript
JavaScript Math.ceil 方法(对数值向上取整)
Jan 09 Javascript
JavaScript驾驭网页-CSS与DOM
Mar 24 Javascript
vue获取DOM元素并设置属性的两种实现方法
Sep 30 Javascript
JS实现获取数组中最大值或最小值功能示例
Mar 02 Javascript
使用typescript改造koa开发框架的实现
Feb 04 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
Prototype中dom对象方法汇总
2008/09/17 Javascript
JSQL 基于客户端的成绩统计实现方法
2010/05/05 Javascript
解析JavaScript中的标签语句
2013/06/19 Javascript
js面向对象之公有、私有、静态属性和方法详解
2015/04/17 Javascript
Javascript对象Clone实例分析
2015/06/09 Javascript
程序员必知35个jQuery 代码片段
2015/11/05 Javascript
JavaScript必知必会(三) String .的方法来自何方
2016/06/08 Javascript
微信小程序 封装http请求实例详解
2017/01/16 Javascript
JavaScript中document.referrer的用法详解
2017/07/04 Javascript
vue和react等项目中更简单的实现展开收起更多等效果示例
2018/02/22 Javascript
ionic2中使用自动生成器的方法
2018/03/04 Javascript
详解解决Vue相同路由参数不同不会刷新的问题
2018/10/12 Javascript
Angular7创建项目、组件、服务以及服务的使用
2019/02/19 Javascript
JS面向对象之单选框实现
2020/01/17 Javascript
JS实现烟花爆炸效果
2020/03/10 Javascript
vue 实现在同一界面实现组件的动态添加和删除功能
2020/06/16 Javascript
解决vue单页面多个组件嵌套监听浏览器窗口变化问题
2020/07/30 Javascript
pandas DataFrame 根据多列的值做判断,生成新的列值实例
2018/05/18 Python
python获取代码运行时间的实例代码
2018/06/11 Python
Python 使用 attrs 和 cattrs 实现面向对象编程的实践
2019/06/12 Python
Python+threading模块对单个接口进行并发测试
2019/06/25 Python
详解Python中的正斜杠与反斜杠
2019/08/09 Python
解决安装pyqt5之后无法打开spyder的问题
2019/12/13 Python
python中time tzset()函数实例用法
2021/02/18 Python
CSS3制作皮卡丘动画壁纸的示例
2020/11/02 HTML / CSS
专注澳大利亚特产和新西兰特产的澳洲中文网:0061澳洲制造
2019/03/24 全球购物
德国排名第一的主题公园门票网站:Attraction Tickets Direct
2019/09/09 全球购物
意大利香水和化妆品购物网站:Parfimo.it
2019/10/06 全球购物
澳大利亚宠物食品和用品商店:PETstock
2020/01/02 全球购物
一份全面的PHP面试问题考卷
2012/07/15 面试题
PyQt QMainWindow的使用示例
2021/03/24 Python
日语专业个人求职信范文
2014/02/02 职场文书
作风转变心得体会
2014/09/02 职场文书
校园运动会广播稿
2014/10/06 职场文书
看看如何用Python绘制小米新版天价logo
2021/04/20 Python
七个非常实用的Python工具包总结
2021/06/15 Python