单独发送formData

时间:2016-09-25 23:20:37

标签: javascript ajax

好的,这就是我想要实现的目标,(截至目前)我有用户选择图像,图像被调整大小并上传到服务器。我想要做的是选择图像并调整大小后停止脚本。然后我想创建一个功能,以便在我选择时上传已调整大小的图像。原因是我要在我的表单中添加更多输入文本,并且用户已经完成了我然后想要上传带有文件的图像。注意:我还没有添加文本输入,只是希望能够分离上传功能。我不知道如何分离FormData帖子部分

JAVASCRIPT

<script>
function ResizeMe(){
var dataurl = null;
var uniq = 'id' + (new Date()).getTime();
var filesToUpload = document.getElementById('input').files;
var file = filesToUpload[0];

// Create an image
var img = document.createElement("img");
// Create a file reader
var reader = new FileReader();
// Set the image once loaded into file reader
reader.onload = function(e)
{
    img.src = e.target.result;

    img.onload = function () {
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        var MAX_WIDTH = 200;
        var MAX_HEIGHT = 400;
        var width = img.width;
        var height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);
        dataurl = canvas.toDataURL("image/jpeg",.2);
        var blobBin = atob(dataurl.split(',')[1]);
        var array = [];
        for(var i = 0; i < blobBin.length; i++) {
        array.push(blobBin.charCodeAt(i));
        }
       var files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: "ddd"});
        // Post the data
        var fd = new FormData();
        fd.append("image", files, uniq);
        $.ajax({
            url: 'http:///www.***/upload.php',
            data: fd,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(data){
                $('#form_input')[0].reset();
                location.reload();
            }
        });
    } // img.onload
}
// Load files into file reader
reader.readAsDataURL(file);
}
</script>

1 个答案:

答案 0 :(得分:1)

发送formdata的代码是

$.ajax({
    url: 'http:///www.***/upload.php',
    data: fd,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        $('#form_input')[0].reset();
        location.reload();
    }
});

该代码是您希望放在单独函数中的代码。要将其移动到其他位置,您必须确保它仍然可以访问所有要发送的变量,即fdfd与几个变量相关联,所有变量都返回canvas。你说一次只有一个画布,所以我们可以使canvas成为一个全局变量,然后从任何地方获取fd都很容易。

<script>
  //Moved to global so that sendFormStuff will see it
  var canvas = document.createElement("canvas");
  var ctx = canvas.getContext("2d");
  function ResizeMe(){
    var dataurl = null;
    var uniq = 'id' + (new Date()).getTime();
    var filesToUpload = document.getElementById('input').files;
    var file = filesToUpload[0];

    // Create an image
    var img = document.createElement("img");
    // Create a file reader
    var reader = new FileReader();
    // Set the image once loaded into file reader
    reader.onload = function(e)
    {
      img.src = e.target.result;

      img.onload = function () {

        ctx.drawImage(img, 0, 0);

        var MAX_WIDTH = 200;
        var MAX_HEIGHT = 400;
        var width = img.width;
        var height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(img, 0, 0, width, height);
      } // img.onload
    }
    function sendFormStuff() {
      var dataurl = canvas.toDataURL("image/jpeg",.2);
      var blobBin = atob(dataurl.split(',')[1]);
      var array = [];
      for(var i = 0; i < blobBin.length; i++) {
        array.push(blobBin.charCodeAt(i));
      }
      var files = new Blob([new Uint8Array(array)], {type: 'image/jpg', name: "ddd"});
      // Post the data
      var fd = new FormData();
      fd.append("image", files, uniq);
      $.ajax({
        url: 'http:///www.***/upload.php',
        data: fd,
        cache: false,
        contentType: false,
        processData: false,
        type: 'POST',
        success: function(data){
          $('#form_input')[0].reset();
          location.reload();
        }
      });
    }
    // Load files into file reader
    reader.readAsDataURL(file);
  }
</script>

所以我们在这里所做的就是将请求代码移动到一个单独的函数中,并使该函数可以访问canvasctx(您声明两次,顺便说一句)。