I have a form page that has a file upload field and I am trying to set the value of that field programmatically and although I know that it isn't possible due to security reasons, I would like to know if we still can? If there is a plugin or something that I could use to perform the upload. I have the Base64 value of the file field that is required to set that field, all I need to know is if there is a way to set it.
Any suggestions or help would be great in this regard.
Thanks.
Update: Added a JsFiddle to demonstrate what I'm trying out.
Please visit this website to create a text file using the example in the js fiddle and convert it using this link.
var str = `text`;
http://www.motobit.com/util/base64-decoder-encoder.asp
JsFiddle
Note:
The answer(s) below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript in 2017.
See the answer in this question for details as well as a demo:
How to set file input value programatically (i.e.: when drag-dropping files)?
You can convert the base64 string to a blob and then add it to the formData before submitting it with an ajax request:
$("#form").submit(function(e) {
e.preventDefault();
formData = new FormData($(this)[0]);
var blob = dataURLtoBlob("base64 string");
formData.append("yourfile", blob);
$.ajax({
url: "whatever.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
alert("Form has been submitted with file");
}
});
dataURLtoBlob is a function that converts the base64 string to the binary file (blob) source: Blob from DataURL?
Update: Added a JsFiddle to demonstrate what I'm trying out.
@seahorsepip Answer, minimally adjusted to substitute success
for done
which is not a defined $.ajax()
setting, and removing trailing ;
following done:function(){}
, which logs a syntax error, should return expected result. Where convertedvalue
at linked jsfiddle at updated Question is also adjusted to a valid data URI
. That is, after converting string to base64
, use the "data" URL scheme to convert base64
string to valid data URI
; e.g.,
"data:text/plain;base64," + convertedvalue
Note, File
object created at FormData
is requested with GET
and returned at success
at stacksnippets and jsfiddle to demonstrate file within FormData
POST
ed by $.ajax()
var convertedvalue = btoa(str); // where `str` is string
$("#form").submit(function(e) {
e.preventDefault();
formData = new FormData($(this)[0]);
// pass valid `data URI` to `dataURItoBlob`
// note `base64` extension
var blob = dataURItoBlob("data:text/plain;base64," + convertedvalue);
formData.append("yourfile", blob);
$.ajax({
url: "/path/to/server",
type: "POST",
data: formData,
contentType: false,
cache: true,
processData: false,
// substitute `success` for `done`
success: function(data) {
//alert("Form has been submitted with file");
} // remove trailing `;`
});
})
var str = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit pharetra ante, quis tristique elit tempor at. Mauris nec nisi porttitor, sodales nunc facilisis, tempor ligula. Aenean luctus purus id orci commodo, eu ornare erat molestie. Proin viverra semper est, sit amet hendrerit mi. Phasellus sodales auctor ipsum eu fermentum. Quisque ut convallis turpis. Suspendisse et varius lorem. Quisque ipsum metus, venenatis quis aliquam et, lobortis nec purus. Aenean consectetur, tellus in gravida tempor, dui lacus placerat dui, quis dictum libero sapien at diam. Donec eleifend, turpis ac vulputate vulputate, nulla enim vestibulum magna, nec finibus ex urna sed quam. Curabitur vitae felis mi. Suspendisse potenti.
Quisque scelerisque mattis venenatis. Phasellus in varius lectus. Ut ut lorem eu augue convallis vulputate. Ut at tortor leo. Etiam tristique, quam et ultrices commodo, risus mauris mollis nisi, quis condimentum sapien tortor et dolor. Pellentesque sollicitudin velit ut sapien tristique, in mattis est facilisis. Pellentesque et leo massa. Sed pretium faucibus purus ac sodales. Sed varius eros felis, vel posuere metus lobortis id. Maecenas eget cursus ligula. In nec luctus orci. Nunc sed massa elit. Pellentesque iaculis tortor sit amet tellus ultrices, nec tristique lorem semper.
Donec aliquet ipsum ipsum, in consequat nisl euismod nec. Aenean aliquam nisl nec elit convallis pulvinar. Suspendisse ac malesuada ex. Fusce laoreet metus at nulla suscipit, non facilisis dui scelerisque. Maecenas blandit augue et lorem venenatis consequat. In porttitor eros ac elit placerat sodales. Suspendisse facilisis lorem vestibulum ante commodo dignissim. Mauris dignissim egestas massa, sit amet hendrerit orci molestie id. Suspendisse vel enim sit amet massa eleifend accumsan. Curabitur eleifend velit non nisi egestas ornare. Ut congue, eros a condimentum faucibus, risus sapien cursus elit, tempor condimentum nisi nisi vitae leo. Sed quis blandit tellus, in aliquet purus. Pellentesque eget leo lobortis, consectetur nisi non, facilisis lectus. Morbi tortor augue, posuere vel ultrices in, vestibulum vel nibh. Morbi accumsan tellus congue commodo tincidunt.
Curabitur vitae fermentum eros. Sed ex dolor, suscipit in ornare in, sollicitudin ac mi. Phasellus ornare ipsum vel elit mollis convallis. Nunc nec porttitor tellus. Nullam volutpat leo sed dapibus vestibulum. Ut aliquet accumsan nulla, commodo pharetra urna auctor in. In ligula lectus, molestie a libero a, sollicitudin rutrum tellus.
Integer vitae turpis id ligula eleifend laoreet. Morbi molestie libero non interdum pulvinar. Nulla facilisi. Nulla a facilisis velit. Etiam metus felis, fermentum eget massa eu, posuere vestibulum mauris. Donec placerat faucibus sapien, vitae dapibus est dapibus ac. Nam quis elementum eros, a eleifend erat. Sed interdum nisi at rhoncus rutrum. Phasellus vitae arcu a tellus tincidunt mattis.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit pharetra ante, quis tristique elit tempor at. Mauris nec nisi porttitor, sodales nunc facilisis, tempor ligula. Aenean luctus purus id orci commodo, eu ornare erat molestie. Proin viverra semper est, sit amet hendrerit mi. Phasellus sodales auctor ipsum eu fermentum. Quisque ut convallis turpis. Suspendisse et varius lorem. Quisque ipsum metus, venenatis quis aliquam et, lobortis nec purus. Aenean consectetur, tellus in gravida tempor, dui lacus placerat dui, quis dictum libero sapien at diam. Donec eleifend, turpis ac vulputate vulputate, nulla enim vestibulum magna, nec finibus ex urna sed quam. Curabitur vitae felis mi. Suspendisse potenti.
Quisque scelerisque mattis venenatis. Phasellus in varius lectus. Ut ut lorem eu augue convallis vulputate. Ut at tortor leo. Etiam tristique, quam et ultrices commodo, risus mauris mollis nisi, quis condimentum sapien tortor et dolor. Pellentesque sollicitudin velit ut sapien tristique, in mattis est facilisis. Pellentesque et leo massa. Sed pretium faucibus purus ac sodales. Sed varius eros felis, vel posuere metus lobortis id. Maecenas eget cursus ligula. In nec luctus orci. Nunc sed massa elit. Pellentesque iaculis tortor sit amet tellus ultrices, nec tristique lorem semper.
Donec aliquet ipsum ipsum, in consequat nisl euismod nec. Aenean aliquam nisl nec elit convallis pulvinar. Suspendisse ac malesuada ex. Fusce laoreet metus at nulla suscipit, non facilisis dui scelerisque. Maecenas blandit augue et lorem venenatis consequat. In porttitor eros ac elit placerat sodales. Suspendisse facilisis lorem vestibulum ante commodo dignissim. Mauris dignissim egestas massa, sit amet hendrerit orci molestie id. Suspendisse vel enim sit amet massa eleifend accumsan. Curabitur eleifend velit non nisi egestas ornare. Ut congue, eros a condimentum faucibus, risus sapien cursus elit, tempor condimentum nisi nisi vitae leo. Sed quis blandit tellus, in aliquet purus. Pellentesque eget leo lobortis, consectetur nisi non, facilisis lectus. Morbi tortor augue, posuere vel ultrices in, vestibulum vel nibh. Morbi accumsan tellus congue commodo tincidunt.
Curabitur vitae fermentum eros. Sed ex dolor, suscipit in ornare in, sollicitudin ac mi. Phasellus ornare ipsum vel elit mollis convallis. Nunc nec porttitor tellus. Nullam volutpat leo sed dapibus vestibulum. Ut aliquet accumsan nulla, commodo pharetra urna auctor in. In ligula lectus, molestie a libero a, sollicitudin rutrum tellus.
Integer vitae turpis id ligula eleifend laoreet. Morbi molestie libero non interdum pulvinar. Nulla facilisi. Nulla a facilisis velit. Etiam metus felis, fermentum eget massa eu, posuere vestibulum mauris. Donec placerat faucibus sapien, vitae dapibus est dapibus ac. Nam quis elementum eros, a eleifend erat. Sed interdum nisi at rhoncus rutrum. Phasellus vitae arcu a tellus tincidunt mattis.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras suscipit pharetra ante, quis tristique elit tempor at. Mauris nec nisi porttitor, sodales nunc facilisis, tempor ligula. Aenean luctus purus id orci commodo, eu ornare erat molestie. Proin viverra semper est, sit amet hendrerit mi. Phasellus sodales auctor ipsum eu fermentum. Quisque ut convallis turpis. Suspendisse et varius lorem. Quisque ipsum metus, venenatis quis aliquam et, lobortis nec purus. Aenean consectetur, tellus in gravida tempor, dui lacus placerat dui, quis dictum libero sapien at diam. Donec eleifend, turpis ac vulputate vulputate, nulla enim vestibulum magna, nec finibus ex urna sed quam. Curabitur vitae felis mi. Suspendisse potenti.
Quisque scelerisque mattis venenatis. Phasellus in varius lectus. Ut ut lorem eu augue convallis vulputate. Ut at tortor leo. Etiam tristique, quam et ultrices commodo, risus mauris mollis nisi, quis condimentum sapien tortor et dolor. Pellentesque sollicitudin velit ut sapien tristique, in mattis est facilisis. Pellentesque et leo massa. Sed pretium faucibus purus ac sodales. Sed varius eros felis, vel posuere metus lobortis id. Maecenas eget cursus ligula. In nec luctus orci. Nunc sed massa elit. Pellentesque iaculis tortor sit amet tellus ultrices, nec tristique lorem semper.
Donec aliquet ipsum ipsum, in consequat nisl euismod nec. Aenean aliquam nisl nec elit convallis pulvinar. Suspendisse ac malesuada ex. Fusce laoreet metus at nulla suscipit, non facilisis dui scelerisque. Maecenas blandit augue et lorem venenatis consequat. In porttitor eros ac elit placerat sodales. Suspendisse facilisis lorem vestibulum ante commodo dignissim. Mauris dignissim egestas massa, sit amet hendrerit orci molestie id. Suspendisse vel enim sit amet massa eleifend accumsan. Curabitur eleifend velit non nisi egestas ornare. Ut congue, eros a condimentum faucibus, risus sapien cursus elit, tempor condimentum nisi nisi vitae leo. Sed quis blandit tellus, in aliquet purus. Pellentesque eget leo lobortis, consectetur nisi non, facilisis lectus. Morbi tortor augue, posuere vel ultrices in, vestibulum vel nibh. Morbi accumsan tellus congue commodo tincidunt.
Curabitur vitae fermentum eros. Sed ex dolor, suscipit in ornare in, sollicitudin ac mi. Phasellus ornare ipsum vel elit mollis convallis. Nunc nec porttitor tellus. Nullam volutpat leo sed dapibus vestibulum. Ut aliquet accumsan nulla, commodo pharetra urna auctor in. In ligula lectus, molestie a libero a, sollicitudin rutrum tellus.
Integer vitae turpis id ligula eleifend laoreet. Morbi molestie libero non interdum pulvinar. Nulla facilisi. Nulla a facilisis velit. Etiam metus felis, fermentum eget massa eu, posuere vestibulum mauris. Donec placerat faucibus sapien, vitae dapibus est dapibus ac. Nam quis elementum eros, a eleifend erat. Sed interdum nisi at rhoncus rutrum. Phasellus vitae arcu a tellus tincidunt mattis.
Images:
1) Copy and replace the following files in the /images folder
i. 1icon.png
ii. 2icon.png
iii. 3icon.png
iv. mobil-app.png
v. mobil-app-this.png
vi. properties-icon.svgz
vii. setupLogo.svgz
viii. web-app.png
ix. web-app-this.png`;
var convertedvalue = btoa(str);
console.log(convertedvalue);
$("#b64text").html(convertedvalue);
$("input[type=submit]").prop("disabled", false);
function dataURItoBlob(dataURI) {
// convert base64 to raw binary data held in a string
// doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
var byteString = atob(dataURI.split(',')[1]);
// separate out the mime component
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
// write the bytes of the string to an ArrayBuffer
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var blob = new Blob([ab], {
type: mimeString
});
return blob;
// Old code
// var bb = new BlobBuilder();
// bb.append(ab);
// return bb.getBlob(mimeString);
}
$("#form").submit(function(e) {
e.preventDefault();
formData = new FormData($(this)[0]);
// pass valid `data URI` to `dataURItoBlob`
var blob = dataURItoBlob("data:text/plain;base64," + convertedvalue);
formData.append("yourfile", blob);
$.ajax({
url: URL.createObjectURL(formData.get("yourfile")),
type: "GET",
// data: formData,
contentType: false,
cache: true,
processData: false,
success: function(data) {
console.log(data);
$("#b64text").html(data);
//alert("Form has been submitted with file");
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<form id="form">
<input type="submit" disabled/>
</form>
<div id="b64text" style=" word-wrap: break-word;">
</div>
jsfiddle https://jsfiddle.net/rccfymrz/17/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With