Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - Attach a blob to an input of type file in a form

How to append blob to input of type file?

<!-- Input of type file -->
<input type="file" name="uploadedFile" id="uploadedFile" accept="image/*"><br>
// I am getting image from webcam and converting it to a blob
function takepicture() {
    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(video, 0, 1, width, height);
    var data = canvas.toDataURL('image/png');
    var dataURL = canvas.toDataURL();
    var blob = dataURItoBlob(dataURL);
    photo.setAttribute('src', data);
}

function dataURItoBlob(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
        return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
    }

    // How can I append this var blob to "uploadedFile". I want to add this on form submit

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is possible to set value of <input type="file">.

To do this you create File object from blob and new DataTransfer object:

let file = new File([data], "img.jpg",{type:"image/jpeg", lastModified:new Date().getTime()});
let container = new DataTransfer();

Then you add file to container thus populating its 'files' property, which can be assigned to 'files' property of file input:

container.items.add(file);
fileInputElement.files = container.files;

Here is a fiddle with output, showing that file is correctly placed into input. The file is also passed correctly to server on form submit. This works at least on Chrome 88.

If you need to pass multiple files to input you can just call container.items.add multiple times. So you can add files to input by keeping track of them separately and overwriting its 'files' property as long as this input contains only generated files (meaning not selected by user). This can be useful for image preprocessing, generating complex files from several simple ones (e.g. pdf from several images), etc.

API references:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...