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 相关文章推荐
jQuery 1.0.2
Oct 11 Javascript
浏览器解析js生成的html出现样式问题的解决方法
Apr 16 Javascript
JavaScript实现将xml转换成html table表格的方法
Apr 17 Javascript
jQuery取得iframe中元素的常用方法详解
Jan 14 Javascript
基于JavaScript短信验证码如何实现
Jan 24 Javascript
浅谈javascript运算符——条件,逗号,赋值,()和void运算符
Jul 15 Javascript
AngularJS压缩JS技巧分析
Nov 08 Javascript
如何在Angular2中使用jQuery及其插件的方法
Feb 09 Javascript
JavaScript 基础表单验证示例(纯Js实现)
Jul 20 Javascript
微信小程序实现展示评分结果功能
Feb 15 Javascript
layui使用数据表格实现购物车功能
Jul 26 Javascript
详解Vue 的异常处理机制
Nov 30 Vue.js
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
让PHP开发者事半功倍的十大技巧小结
2010/04/20 PHP
由php的call_user_func传reference引发的思考
2010/07/23 PHP
YII框架批量插入数据的方法
2017/03/18 PHP
Ajax+PHP实现的模拟进度条功能示例
2019/02/11 PHP
javascript 异常处理使用总结
2009/06/21 Javascript
用客户端js实现带省略号的分页
2013/04/27 Javascript
jquery实现侧边弹出的垂直导航
2014/12/09 Javascript
node.js中的fs.fchmod方法使用说明
2014/12/16 Javascript
jQuery中 prop() attr()使用详解
2015/05/19 Javascript
深入理解JavaScript程序中内存泄漏
2016/03/17 Javascript
纯js实现瀑布流布局及ajax动态新增数据
2016/04/07 Javascript
搭建简单的nodejs http服务器详解
2017/03/09 NodeJs
详解JS数据类型的值拷贝函数(深拷贝)
2017/07/13 Javascript
js单页hash路由原理与应用实战详解
2017/08/14 Javascript
Nuxt配合Node在实际生产中的应用详解
2018/08/07 Javascript
浅谈微信页面入口文件被缓存解决方案
2018/09/29 Javascript
vue-cli3使用 DllPlugin 实现预编译提升构建速度
2019/04/24 Javascript
详解如何使用router-link对象方式传递参数?
2019/05/02 Javascript
vue+ts下对axios的封装实现
2020/02/18 Javascript
实例分析javascript中的异步
2020/06/02 Javascript
Python基础教程之正则表达式基本语法以及re模块
2016/03/25 Python
python中实现迭代器(iterator)的方法示例
2017/01/19 Python
Python读取txt某几列绘图的方法
2018/10/14 Python
Python OpenCV实现视频分帧
2019/06/01 Python
HTML中fieldset标签概述及使用方法
2013/02/01 HTML / CSS
德国家具购物网站:Möbel Höffner
2019/08/26 全球购物
广州品高软件.net笔面试题目
2012/04/18 面试题
客服专员岗位职责范本
2013/11/29 职场文书
幼儿园社区活动总结
2014/07/07 职场文书
2014年工作总结与下年工作计划
2014/11/27 职场文书
2015年销售内勤工作总结
2015/04/27 职场文书
Linux安装Nginx步骤详解
2021/03/31 Servers
Python如何利用正则表达式爬取网页信息及图片
2021/04/17 Python
JDBC连接的六步实例代码(与mysql连接)
2021/05/12 MySQL
解析在浏览器地址栏输入一个URL后发生了什么
2021/06/21 Servers
Nebula Graph解决风控业务实践
2022/03/31 MySQL