且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

FormData中的Blob为空

更新时间:2023-02-24 21:19:04

我最近还没有做过,但这对我有用.我希望它也对您有用:

I've not done this recently, but this works with me. I hope it also works with you:

function getBase64ImageByURL(url) {
  var dfd = new $.Deferred();
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function() {
    var reader = new FileReader();
    reader.onloadend = function() {
      dfd.resolve(reader.result);
    }
    reader.readAsDataURL(xhr.response);
  };
  xhr.open('GET', url);
  xhr.send();
  return dfd.promise();
}

function base64ToBlob(base64Image,toMimeType) {
  var byteCharacters = atob(base64Image.replace('data:'+toMimeType+';base64,',''));
  var byteNumbers = new Array(byteCharacters.length);
  for (var i = 0; i < byteCharacters.length; i++) {
    byteNumbers[i] = byteCharacters.charCodeAt(i);
  }
  var byteArray = new Uint8Array(byteNumbers);
  var blob = new Blob([byteArray], {
    type: toMimeType
  });
  return blob;
}



var imageUrl = "https://upload.wikimedia.org/wikipedia/commons/4/49/Koala_climbing_tree.jpg";

getBase64ImageByURL(imageUrl).then(function(base64Image){
  var blob = base64ToBlob(base64Image,'image/jpeg');
  var fd = new FormData();
  fd.append('file', blob, 'my_image.jpg');
  $.ajax({
    url: 'http://your_host/uploads/testupload.php',
    data: fd,
    type: 'POST',
    contentType: false,
    processData: false,
    success:function(res){
      console.log(res);
    },
    error:function(err){
      console.log(err);
    }
  })
});

在服务器端(testupload.php):

On server-side(testupload.php):

<?php

    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        $result = move_uploaded_file($_FILES['file']['tmp_name'], $_SERVER["DOCUMENT_ROOT"].$_SERVER["BASE"].'/uploads/'.'my_image.jpg');
        var_dump("image uploaded: ".$result);
    }

?>

move_uploaded_file 成功将上传的图像移动到该目录之前,可能需要修改目录上的某些读/写权限.

It might be necessary to modify some read/write-permissions on a directory before move_uploaded_file succeeds in moving the uploaded image to this directory.

函数 getBase64ImageByURL 已经可以返回blob对象,但是通过返回base64-image,您可以在上传html-image-tag之前向用户显示该图像.

The function getBase64ImageByURL could already return a blob-object but by returning a base64-image you can show an user this image in a html-image-tag before uploading it for instance.

如果不需要向用户显示该图像,那么您还可以缩短所有步骤:

If there is no need to show an user that image, then you can also shorten all steps:

function getBlobImageByURL(url) {
  var dfd = new $.Deferred();
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'blob';
  xhr.onload = function() {
    dfd.resolve(xhr.response);
  };
  xhr.open('GET', url);
  xhr.send();
  return dfd.promise();
}

getBlobImageByURL(imageUrl).then(function(imageBlob){
  var fd = new FormData();
  fd.append('file', imageBlob, 'my_image.jpg');
  console.log(fd.get('file'));// File-object 
  $.ajax({
    url: 'http://your_host/uploads/testupload.php',
    data: fd,
    type: 'POST',
    contentType: false,
    processData: false,
    success:function(res){
      console.log(res);
    },
    error:function(err){
      console.log(err);
    }
  })
});

对两个已修改函数的引用 base64ToBlob getBase64ImageByURL

references to both modified functions base64ToBlob and getBase64ImageByURL