converting dataURI to File to use in Parse - javascript

对着背影说爱祢 提交于 2019-12-23 21:43:53

问题


I was able to follow some steps to create a canvas element from a selected image file, then create an image from that canvas element. I need to do this so the image sent to parse isnt a huge file.

Now I need to be able to access that image in the form of a file and upload through parse. I'm a bit stuck as far as how to go about accessing the blob that's is created.

consider this:

//upload post
$('#fileselect').bind('change', function(e) {
  readURL(this);
  setTimeout(function() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    img = new Image();
    img.onload = function() {
      canvas.height = canvas.width * (img.height / img.width);
  /// step 1
      var oc = document.createElement('canvas'),
      octx = oc.getContext('2d');
      oc.width = img.width * 0.5;
      oc.height = img.height * 0.5;
      octx.drawImage(img, 0, 0, oc.width, oc.height);
  /// step 2
      octx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5);
      ctx.drawImage(oc, 0, 0, oc.width * 0.5, oc.height * 0.5, 0, 0, canvas.width, canvas.height);
    }
    img.src = $(".previewupload").attr('src');
    var image2 = $('.imagereceive');

setTimeout(function() {

  var canvurl = canvas.toDataURL("image/png");
  image2.attr('src', canvurl);
  var name = "image1.jpg"; //This does *NOT* need to be a unique name
  var dataURL = canvas.toDataURL('image/jpeg', 0.5);
  var blob = dataURItoBlob(dataURL);
  var fd = new FormData(document.forms[0]);
  fd.append("canvasImage", blob);
  var file = fd;
  var name = "image1.jpg"; //This does *NOT* need to be a unique name
  var parseFile = new Parse.File(name, file);

  $(this).attr('data-name', nameCurrent);
  var imgname = $(this).attr('data-name');

  $('#uploadbutton').click(function(e) {
    var currentUser = Parse.User.current();
    var statusupdate = $('#statusupdateform').val();
    parseFile.save().then(function() {
      var nameCurrent = currentUser.getUsername();
      var wall = new Parse.Object("wall");
      wall.set("imagefile", parseFile);
      wall.save({
        success: function() {
          alert(parseFile.url());
        },
        error: function() {
          alert("upload failed. please try again!");
        }
       });
     });
   });
  }, 200);
 }, 1000);
});

Thank you for any suggestions/help

UPDATED

solved by adding the following lines

        var base64 = dataURL.split('base64,')[1];
        var parseFile = new Parse.File(name, { base64: base64 });

来源:https://stackoverflow.com/questions/26024135/converting-datauri-to-file-to-use-in-parse-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!