django & cropper.js &bootstrap 实现头像截取并上传

index.html


{% load staticfiles %}
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> 
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>头像截取title>
<link rel="stylesheet" type="text/css" href="{% static 'css/normalize.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'css/default.css"' %}">
assets/css/bootstrap.min.css' %}" rel="stylesheet">
<link href="{% static 'dist/cropper.css' %}" rel="stylesheet">

<link href="{% static 'css/main.css' %}"  rel="stylesheet">

head>
<body>
<div class="htmleaf-container">
    
<div class="container">
<div class="row">
<form id="uploadForm">
  <div class="col-md-9">
    
    <div class="img-container">
       <img src="{% static 'assets/img/pic.jpg' %}" alt="Picture">
    div>
  div>
  <div class="col-md-3">
    
    <div class="docs-preview clearfix">
      <div class="img-preview preview-lg">div>
      <div class="img-preview preview-md">div>
      <div class="img-preview preview-sm">div>
      <div class="img-preview preview-xs">div>
    div>

    
    <div class="docs-data">
      <div class="input-group">
        <label class="input-group-addon" for="dataX">Xlabel>
        <input class="form-control" id="dataX" type="text" placeholder="x" name="x">
        <span class="input-group-addon">pxspan>
      div>
      <div class="input-group">
        <label class="input-group-addon" for="dataY">Ylabel>
        <input class="form-control" id="dataY" type="text" placeholder="y" name="y">
        <span class="input-group-addon">pxspan>
      div>
      <div class="input-group">
        <label class="input-group-addon" for="dataWidth">Widthlabel>
        <input class="form-control" id="dataWidth" type="text" placeholder="width" name="w">
        <span class="input-group-addon">pxspan>
      div>
      <div class="input-group">
        <label class="input-group-addon" for="dataHeight">Heightlabel>
        <input class="form-control" id="dataHeight" type="text" placeholder="height" name="h">
        <span class="input-group-addon">pxspan>
      div>

    div>
  div>
div>
<div class="row">
  <div class="col-md-9 center">
    

    <div class="btn-group" width="80%">
     <label class="btn btn-primary btn-upload" for="inputImage" title="Upload image file" width="80%">
        


        <input class="sr-only"  id="inputImage" name="file" type="file" accept="image/*">
        <span class="docs-tooltip" data-toggle="tooltip" title="Import image with Blob URLs">
          <span>选择span>
        span>
      label>
    div>

    <div class="btn-group">
      <button class="btn btn-primary" id="submit" type="button"  aria-expanded="true">
        <span class="docs-tooltip">
          <span>提交span>
        span>
      button>
    div>
  div>








  <div class="col-md-3 docs-toggles">
    



  div>
 


div>
div>



<script src="{% static 'assets/js/jquery.min.js' %}">script>
<script src="{% static 'assets/js/bootstrap.min.js' %}">script>
<script src="{% static 'dist/cropper.js' %}">script>
<script src="{% static 'js/main.js' %}">script>

body>
html>
<div style="display:none">
    <script type="text/javascript">


     $(function(){
        $("#submit").click(function(){
        //alert("sub");
        x = $("#dataX").val();
        y = $("#dataY").val();
        w = $("#dataWidth").val();
        h = $("#dataHeight").val();
        //alert(imageId);
        //+x+'y='+y+'w='+w+'h='+h

        /*
        $.get('/sub?imageId='+imageId+'&x='+x+'&y='+y+'&w='+w+'&h='+h,function(data){
            if(data=="1"){
                alert("提交成功");
            }else{
                alert("提交失败");
            }
        });
        */
         var formData = new FormData($( "#uploadForm" )[0]);  
         $.ajax({  
              url: '/sub/' ,  
              type: 'POST',  
              data: formData,  
              async: false,  
              cache: false,  
              contentType: false,  
              processData: false,  
              success: function (returndata) {  
                  if(returndata == "1")
                    alert("提交成功");
                  else{
                    alert("提交失败,请重试!");
                  }
              },  
              error: function (returndata) {  
                  alert("提交失败,请重试!");  
              }  
      });  

     });
    });

    script>
div>

main.js

var imageId = "";
$(function () {
  'use strict';

  var console = window.console || { log: function () {} },
      $alert = $('.docs-alert'),
      $message = $alert.find('.message'),
      showMessage = function (message, type) {
        $message.text(message);

        if (type) {
          $message.addClass(type);
        }

        $alert.fadeIn();

        setTimeout(function () {
          $alert.fadeOut();
        }, 3000);
      };

  // Demo
  // -------------------------------------------------------------------------

  (function () {
    var $image = $('.img-container > img'),
        $dataX = $('#dataX'),
        $dataY = $('#dataY'),
        $dataHeight = $('#dataHeight'),
        $dataWidth = $('#dataWidth'),
        $dataRotate = $('#dataRotate'),
        options = {
          mouseWheelZoom: false, //禁用鼠标滑轮缩放
          preview: '.img-preview',
          crop: function (data) {
            $dataX.val(Math.round(data.x));
            $dataY.val(Math.round(data.y));
            $dataHeight.val(Math.round(data.height));
            $dataWidth.val(Math.round(data.width));
            $dataRotate.val(Math.round(data.rotate));
          }
        };

    $image.on({
      'build.cropper': function (e) {
        console.log(e.type);
      },
      'built.cropper': function (e) {
        console.log(e.type);
      },
      'dragstart.cropper': function (e) {
        console.log(e.type, e.dragType);
      },
      'dragmove.cropper': function (e) {
        console.log(e.type, e.dragType);
      },
      'dragend.cropper': function (e) {
        console.log(e.type, e.dragType);
      }
      /*,
      'zoomin.cropper': function (e) {
        console.log(e.type);
      },
      'zoomout.cropper': function (e) {
        console.log(e.type);
      }
      */
    }).cropper(options);


    // Methods
    $(document.body).on('click', '[data-method]', function () {
      var data = $(this).data(),
          $target,
          result;

      if (data.method) {
        data = $.extend({}, data); // Clone a new one

        if (typeof data.target !== 'undefined') {
          $target = $(data.target);

          if (typeof data.option === 'undefined') {
            try {
              data.option = JSON.parse($target.val());
            } catch (e) {
              console.log(e.message);
            }
          }
        }

        result = $image.cropper(data.method, data.option);

        if (data.method === 'getCroppedCanvas') {
          $('#getCroppedCanvasModal').modal().find('.modal-body').html(result);
        }

        if ($.isPlainObject(result) && $target) {
          try {
            $target.val(JSON.stringify(result));
          } catch (e) {
            console.log(e.message);
          }
        }

      }
    }).on('keydown', function (e) {

      switch (e.which) {
        case 37:
          e.preventDefault();
          $image.cropper('move', -1, 0);
          break;

        case 38:
          e.preventDefault();
          $image.cropper('move', 0, -1);
          break;

        case 39:
          e.preventDefault();
          $image.cropper('move', 1, 0);
          break;

        case 40:
          e.preventDefault();
          $image.cropper('move', 0, 1);
          break;
      }

    });


    // Import image
    var $inputImage = $('#inputImage'),
        URL = window.URL || window.webkitURL,
        blobURL;

    if (URL) {
      $inputImage.change(function () {
          //alert("change");
        var files = this.files,
            file;

        if (files && files.length) {
          file = files[0];
          imageId = file.name;

          if (/^image\/\w+$/.test(file.type)) {
            blobURL = URL.createObjectURL(file);
            $image.one('built.cropper', function () {
              URL.revokeObjectURL(blobURL); // Revoke when load complete
            }).cropper('reset', true).cropper('replace', blobURL);
            //$inputImage.val('');
          } else {
            showMessage('Please choose an image file.');
          }
        }
      });
    } else {
      $inputImage.parent().remove();
    }


    // Options
    $('.docs-options :checkbox').on('change', function () {
      var $this = $(this);

      options[$this.val()] = $this.prop('checked');
      $image.cropper('destroy').cropper(options);
    });


    // Tooltips
    $('[data-toggle="tooltip"]').tooltip();

  }());

});

Django后台处理逻辑

def sub(request):
      #return HttpResponse("Hello world ! ")
     #imgName = request.GET.get('url')
     #context['error'] = 'system exception' 
     '''
     if request.method == "POST":
        pf = plateForm(request.POST,request.FILES)
        if pf.is_valid():
            imgName = uf.cleaned_data['username']
            plateImg = uf.cleaned_data['headImg']
            return HttpResponse('upload ok!')
    '''
     x = request.POST.get('x')
     y = request.POST.get('y')
     w = request.POST.get('w')
     h = request.POST.get('h')
     #print(request.FILES['file'])
     imgType = request.FILES['file'].name.split(".")[1]
     imgName = handle_uploaded_file(request.FILES['file'],imgType)
     #print("===>>>",x,y,w,h)
     if(x !=None and y != None and w!= None and h != None):
        line = imgName+"."+imgType+"\t"+x+"\t"+y+"\t"+w+"\t"+h
        with open("plate.txt","a+") as f:
           f.write(line+"\n")
        return HttpResponse("1")
     else:
        return HttpResponse("0")
def handle_uploaded_file(f,ImgType):
   newImageName = str(time.time()).split(".")[0]
   destination = open(BASE_DIR+BASE_IMG_DIR+str(newImageName)+"."+ImgType, 'wb')
   for chunk in f.chunks():
      destination.write(chunk)
   destination.close()
   return newImageName

你可能感兴趣的:(web开发)