Convert HTML5 Canvas into File to be uploaded?

后端 未结 5 1677
生来不讨喜
生来不讨喜 2020-11-28 03:54

The standard HTML file upload works as follows:



        
5条回答
  •  萌比男神i
    2020-11-28 04:29

    For security reasons, you can't set the value of a file-input element directly.

    If you want to use a file-input element:

    1. Create an image from the canvas (as you've done).
    2. Display that image on a new page.
    3. Have the user right-click-save-as to their local drive.
    4. Then they can use your file-input element to upload that newly created file.

    Alternatively, you can use Ajax to POST the canvas data:

    You asked about blob:

    var blobBin = atob(dataURL.split(',')[1]);
    var array = [];
    for(var i = 0; i < blobBin.length; i++) {
        array.push(blobBin.charCodeAt(i));
    }
    var file=new Blob([new Uint8Array(array)], {type: 'image/png'});
    
    
    var formdata = new FormData();
    formdata.append("myNewFileName", file);
    $.ajax({
       url: "uploadFile.php",
       type: "POST",
       data: formdata,
       processData: false,
       contentType: false,
    }).done(function(respond){
      alert(respond);
    });
    

    Note: blob is generally supported in the latest browsers.

提交回复
热议问题