DIV CSS 佈局教程網

jcrop + FileAPI 實作純前端圖片上傳、裁剪與預覽
編輯:JavaScript綜合知識     

本文示範一組很實用的組合:FileAPI 負責讀取與處理本機檔案,jcrop 負責框選裁剪區域,兩者搭配就能做到完全不經過伺服器的圖片裁剪與預覽。

方案特性

  • 先在使用者端完成裁剪,只把結果上傳,大幅降低頻寬與伺服器負擔。
  • 先驗證格式與大小,不符合條件的檔案直接退回,不必等上傳完才發現問題。
  • 新版瀏覽器使用 Canvas 進行裁剪;IE6/7/8 則自動退回 Flash 方案作為過渡。

核心流程

整個流程可以拆成五個階段:監聽 change 事件 → 取得檔案清單 → 過濾格式與大小 → 縮圖並掛上 jcrop → 依選取範圍產生預覽並上傳。

var el = document.querySelector('input[type="file"]');

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);   // 取得檔案清單

    // 第一步:先驗證
    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;
      }
      return true;
    },

    // 第二步:處理通過驗證的檔案
    function (files, rejected) {
      if (!files.length) return;

      var file = files[0];
      var img0 = FileAPI.Image(file);   // 用於顯示與裁剪
      var img1 = FileAPI.Image(file);   // 用於產生裁剪結果
      var ratio = 0;

      // 取得原始尺寸,算出縮放比例
      FileAPI.getInfo(file, function (err, info) {
        if (!err) {
          ratio = info.width > info.height
                ? info.width  / 500
                : info.height / 500;
        }
      });

      // 縮到最長邊 500px,掛上 jcrop
      img0.resize(500, 500, 'max').get(function (err, img) {
        $('#img2').empty().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').html($(img));   // 即時預覽裁剪結果
            });
          }
        });
      });

      // 點擊上傳
      $('#btn').on('click', function () {
        FileAPI.upload({
          url: '/testUpFile/upFile',
          files: { images: img1 },
          progress: function (evt) { /* 進度條可在此更新 */ },
          complete: function (err, xhr) { /* 處理回應 */ }
        });
      });
    });
  });
});

完整可執行的頁面

<!DOCTYPE html>
<html>
<head>
<title>圖片上傳裁剪預覽</title>
<meta charset="UTF-8">
<script src="./jquery.min.js"></script>
<script src="./jcrop/jquery.Jcrop.min.js"></script>
<link href="./jcrop/jquery.Jcrop.min.css" rel="stylesheet">
<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;
    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>
</head>
<body>
<div>
  <!-- js-fileapi-wrapper 這個 class 是 FileAPI 必要的 -->
  <div class="js-fileapi-wrapper upload-btn" id="choose">
    <input name="files" type="file" multiple />
    <button id="btn">上傳</button>
  </div>

  <div id="images">
    <div id="img2"></div>   <!-- 原圖 + 裁剪框 -->
    <div id="img3"></div>   <!-- 裁剪預覽 -->
  </div>
</div>

<script>window.FileAPI = { staticPath: './fileapi/' };</script>
<script src="./fileapi/FileAPI.min.js"></script>
</body>
</html>

實務提醒

  • ratio 的計算時機。FileAPI.getInfo 是非同步的,若在回呼之前就觸發 jcrop 的 onSelect,ratio 可能還是 0,導致裁剪座標全錯。較穩妥的做法是把 jcrop 的初始化寫在 getInfo 的回呼裡。
  • 伺服器端仍要驗證。前端檢查只是使用者體驗,任何輸入都可能在被繞過後送進後端,格式、大小、實際 MIME 都必須在伺服器端重新確認一次。
  • img2 與 img3 的用途要分清。img2 是「顯示用縮圖 + 裁剪框」,img3 是「依 matrix 參數重新渲染後的成品」,兩者用不同的 FileAPI.Image 實例,避免互相污染狀態。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved