Programmatically Set Input Type="file" Value To Base64 Image?
I'm aware of the security reasons that local file cannot be set as a file programmatically to input field. Suppose I've this image as base64: var bus = 'data:image/gif;base64,R0lGO
Solution 1:
No you can't set the value of a file input*, except to clear it, but it sounds that it's not what you need anyway.
Instead, convert this dataURI to a Blob, then append this Blob to a FormData and finally post this FormData.
Your image will be sent as multipart like you seem to need.
functiondataURItoBlob(data) {
var binStr = atob(data).split(',')[1],
len = binStr.length,
arr = newUint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
returnnewBlob(arr);
}
var dataURI = 'data:image/....';
var blob = dataURItoBlob(dataURI);
// you can even pass a <form> in this constructor to add other fieldsvar formData = newFormData();
formData.append('yourFileField', blob, 'fileName.ext');
var xhr = newXMLHttpRequest();
xhr.open('post', yourServer);
xhr.send(formData);
// now you can retrieve your image as a File/multipart with the 'yourFileField' post name
*Actually now you can do it, but it's still rather hackish.
Solution 2:
You can try like below one. Convert your sting to Blob and create file type with created Blob.
var debug = {hello: "world"};
var blob = newBlob([JSON.stringify(debug, null, 2)], {type : 'application/json'});
var outputfile=newFile([blob], "filename")
Post a Comment for "Programmatically Set Input Type="file" Value To Base64 Image?"