There is a function that triggers the input file and shows previews:
$(document).on("change", "#Multifileupload", function() {
var MultifileUpload = document.getElementById("Multifileupload");
if (typeof FileReader != "undefined") {
var MultidvPreview = document.getElementById("MultidvPreview");
console.log(MultifileUpload.files);
var images = Array.prototype.slice.call(
MultifileUpload.files,
0,
upload_product_images_comment_total
);
for (
var i = 0; i < images.length &&
upload_product_images_comment_loaded <=
upload_product_images_comment_total; i++
) {
var file = images[i];
var reader = new FileReader();
reader.onload = function(e) {
var img = document.createElement("img");
var span = document.createElement("span");
span.classList.add("remove_image");
span.classList.add("icon-close");
img.src = e.target.result;
img.classList.add("Multifileupload_image");
var position = upload_product_images_comment_loaded + 1;
if (position > upload_product_images_comment_total - 1) {
var li = document.createElement("li");
$(".upload-photo-thumb").hide();
MultidvPreview.prepend(li);
MultidvPreview.children[0].appendChild(img);
MultidvPreview.children[0].appendChild(span);
} else {
MultidvPreview.children[position].appendChild(img);
MultidvPreview.children[position].appendChild(span);
}
upload_product_images_comment_loaded++;
};
reader.readAsDataURL(file);
}
MultifileUpload.value = '';
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
The HTML input is:
<input type="file" id="Multifileupload" multiple="" name="file" size="40" accept=".png, .jpg, .jpeg, .gif">
Problem is when I choose some images and submit form I get empty file field in request:
csrf_mds_token=b2c47be75606853053acbbcf48c6280c&review=wreewrewrewrwrwrwrwr&rating=5&product_id=6&file=&sys_lang_id=1
You can not send files with the GET method, you have to use POST and add enctype="multipart/form-data" to your form tag:
<form method="POST" enctype="multipart/form-data">
Related
I've below code where user can upload text file. I tried to display output in div after splitting it using # as split character. Array elements stored into variables are displayed correctly with new line in alert but are printed in a single line in div.
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var test = evt.target.result;
var htmlstring = test.split('#');
var data = htmlstring.join('\r\n');
document.getElementById('byte_content').textContent = data;
alert(data); //with line-break
alert(htmlstring); // without line-break
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
}
}, false);
#byte_content {
margin: 5px 0;
max-height: 100px;
overflow-y: auto;
overflow-x: hidden;
}
#byte_range { margin-top: 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="files" name="file" /> Read bytes:
<span class="readBytesButtons">
<button>entire file</button>
</span>
<div id="byte_content"></div>
Text file data:
this is some text #2135311 164 #df fdg
Current output:
this is some text 2135311 164 df fdg
Desired output:
this is some text
2135311 164
df fdg
You need to render data in HTML not plain text:
Instead of \r\n use <br>.
Instead of .textContent use innerHTML
var data = htmlstring.join('<br>');
document.getElementById('byte_content').innerHTML = data;
Demo
function readBlob(opt_startByte, opt_stopByte) {
var files = document.getElementById('files').files;
if (files.length < 1) {
alert('Please select a file!');
return;
}
var file = files[0];
var start = parseInt(opt_startByte) || 0;
var stop = parseInt(opt_stopByte) || file.size - 1;
var reader = new FileReader();
// If we use onloadend, we need to check the readyState.
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
var test = evt.target.result;
var htmlstring = test.split('#');
var data = htmlstring.join('<br>');
document.getElementById('byte_content').innerHTML = data;
alert(data); //with line-break
alert(htmlstring); // without line-break
}
};
var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
}
document.querySelector('.readBytesButtons').addEventListener('click', function(evt) {
if (evt.target.tagName.toLowerCase() == 'button') {
var startByte = evt.target.getAttribute('data-startbyte');
var endByte = evt.target.getAttribute('data-endbyte');
readBlob(startByte, endByte);
}
}, false);
#byte_content {
margin: 5px 0;
max-height: 100px;
overflow-y: scroll;
overflow-x: hidden;
}
#byte_range {
margin-top: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="file" id="files" name="file" /> Read bytes:
<span class="readBytesButtons">
<button>entire file</button>
</span>
<div id="byte_content"></div>
Just replacing div with textarea tag to display content it's working fine.
I have 2 image fields and I want to display a preview before submitting the form. In the form below, it works by displaying multiple images, but I want each input to show its images separately as:
Input1
Input 1 images
Input 2
Input2 images
How do I do this?
<input id="fileupload" type="file" name="img_slide" multiple>
<div id="dvPreview">
<input id="fileupload2" type="file" name="img_capa" multiple>
<div id="dvPreview2">
<script>
window.onload = function () {
var fileUpload = document.getElementById("fileupload");
fileUpload.onchange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = document.getElementById("dvPreview");
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var file = fileUpload.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.height = "100";
img.width = "100";
img.src = e.target.result;
dvPreview.appendChild(img);
dvPreview.appendChild(textbox);
}
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
}
};
I tried this and works for me. Code:
<pre>Please enter your files:<input class="fileupload" type="file" name="img_slide" multiple>
<div id="dvPreview"></div></pre>
<input class="fileupload" type="file" name="img_capa" multiple>
<div id="dvPreview2"></div>
window.onload = function () {
var fileUpload = document.getElementsByClassName("fileupload");
for(var i = 0; i < fileUpload.length; i++){
fileUpload[i].onchange = showImgOnChange;
}
}
var showImgOnChange = function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = this.nextElementSibling;
dvPreview.innerHTML = "";
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for (var i = 0; i < this.files.length; i++) {
var file = this.files[i];
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = document.createElement("IMG");
img.height = "100";
img.width = "100";
img.src = e.target.result;
dvPreview.appendChild(img);
dvPreview.appendChild(textbox);
}
reader.readAsDataURL(file);
} else {
alert(file.name + " is not a valid image file.");
dvPreview.innerHTML = "";
return false;
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
}
Now i will explain that code:
i use a single class for every input of that type. Using that class i get all the elements input and at every input i assign onchange the function showImgOnChange (just a trick to associate the same function on change to multiple elements). After that, in the function, to generalize this:
var dvPreview = document.getElementById("dvPreview");
I used this:
var dvPreview = this.nextElementSibling;
This takes the next element to the this element in the DOM. Otherwise you can associate a class to divs wich you would display the images and search for the next elements to this having that class.
Hope it helps
I am trying to have a function which has functions that do the following.
One function to store the files i get with input into the parent functions loadedimages array(loadimages).
One function to show those files in the correct component(showLoadedImages).
And one function to make the correct img file appear on the correct component.
The last function is what i want it to be like(it does not work).
The other two seem ok.
The problem i have is how to make the last function work while using the loadedimages array. You can change what i store in the array , i wouldnt mind.
Here is the JS code:
function imgviewer() {
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
break;
}
loadedimages.push(file);
}
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
var chosenFile = loadedimages[index];
document.getElementById(elem).src = chosenFile;
}
document.getElementById('images').addEventListener('change', function(){
showLoadedImages("main");
}, false);
}
And some HTML
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
<div id="main"></div>
When i call showLoadedImages("main") the images are shown in main div. I want to be able to click those images so that they appear on "willchange" .
This does what you asked for. There are a number of other issues with your code that you might want to address, starting with the images are not thumbnails at all (and shrunken images take just as long to load as the original), but perhaps I'm missing something.
"use strict";
var loadedimages = [];
var lidivs = [];
function loadimages() {
var files = document.getElementById("images").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
if (!file.name.match(/\.(jpg|jpeg|png|gif)$/)) {
continue;
}
loadedimages.push(file);
}
loadedimages.length || alert('THERE IS NO IMAGE IN THIS DIRECTORY.');
}
function showLoadedImages(elem) {
loadimages();
var ld = loadedimages;
//var files = getLoadedImages(); //filelist obj
for (var i = 0; i < ld.length; i++) {
var file = ld[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
// Render thumbnail.
var span = document.createElement(
'span');
span.innerHTML = [
'<img data-index="',
lidivs.length,
'" class="tile" src="',
e.target.result,
'" title="', encodeURI(
file.name), '">'
].join('');
span.addEventListener("click", foo );
document.getElementById(elem).insertBefore(
span, null);
lidivs.push(span);
};
})(file);
// Read in the image file as a data URL.
reader.readAsDataURL(file);
}
}
function showImage(index, elem) {
document.getElementById(elem).src = lidivs[index].children[0].src;
}
function foo(event) {
showImage(event.target.dataset.index, "willchange");
}
function show() {
showLoadedImages("list");
}
function init() {
document.getElementById("images").addEventListener("change", show, false);
}
document.addEventListener( "DOMContentLoaded", init, false );
<body>
<form name="uploadForm">
<input id="images" type="file" webkitdirectory mozdirectory directory name="myFiles"
multiple/>
<span id="list"></span>
</form>
<div id="sidebar1"><img id="willchange" src="images/railaythailand.jpg" width="1200" height="832" alt=""/></div>
</body>
From following code it accepts Single File and process it & display output.but can it be possible to accept multiple files and process & then return output.
<html>
<head>
</head>
<body>
<div>
<label for="text">Choose file</label>
<input id="text" type="file" name="photo">
</div>
<textarea id="finalHTML" style="height:200px;width:80%">
</textarea><br/>
<button id="save">Save</button>
<script>
$('input').change(function(){
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
console.log(e);
selectedImage = e.target.result;
var rawData = reader.result;
console.log(rawData);
var array = {
'<code CLASS="java">j</code>':'⇔',
'<code CLASS="bold">C</code>':'<b>C</b>',
'<code CLASS="italic">g</code>':'',
'<code CLASS="underline">i</code>':'~',
}
var originalText = rawData.toString();
var finalText = originalText;
for (var val in array)
finalText = finalText.replace(new RegExp(val, "g"), array[val]);
console.log(finalText);
$('#finalHTML').text(finalText);
};
reader.readAsBinaryString(this.files[0]);
//reader.readAsDataURL(this.files[0]);
}
});
var button2 = document.getElementById('save');
button2.addEventListener('click', saveTextAsFile);
function saveTextAsFile()
{
var textToWrite = $('#finalHTML').text();
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = "sample1.html"/*Your file name*/;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
</script>
</body>
</html>
I am not able to accept multiple files and process on it,and return Output.
Any one can help me out please.
You used input type 'file' there is an attribute multiple ="multiple" which allows you to select multiple file at once. How to handle those files using JavaScript? you can look at this link ...Multiple-files-selected
try this and look at the for loop block... I'm not tasted it...
$('input').change(function(){
for(var i = 0; i<= files.length; i++){
if (this.files && this.files[i]) {
var reader = new FileReader();
reader.onload = function (e) {
console.log(e);
selectedImage = e.target.result;
var rawData = reader.result;
console.log(rawData);
var array = {
'<code CLASS="java">j</code>':'⇔',
'<code CLASS="bold">C</code>':'<b>C</b>',
'<code CLASS="italic">g</code>':'',
'<code CLASS="underline">i</code>':'~',
}
var originalText = rawData.toString();
var finalText = originalText;
for (var val in array)
finalText = finalText.replace(new RegExp(val, "g"), array[val]);
console.log(finalText);
$('#finalHTML').text(finalText);
};
reader.readAsBinaryString(this.files[i]);
//reader.readAsDataURL(this.files[0]);
}
}
});
I want get the full path image from input file for show image preview and use for example attr of jquery for insert this into scr to this temporal image path , for example i think in that
var filePath = $(this).val();
console.log(filePath);
jQuery('#preview').attr("src",""+img_p);
The problem i don´t know how i can get this temporal path from input file for show and insert this path for the preview image until send to upload in the system
Thank´s , Regards
MOZILLA DEVELOPER NETWORK show us an example to do that:
<input type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
Select some files
<div id="fileList">
<p>No files selected!</p>
</div>
<script>
window.URL = window.URL || window.webkitURL;
var fileSelect = document.getElementById("fileSelect"),
fileElem = document.getElementById("fileElem"),
fileList = document.getElementById("fileList");
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
function handleFiles(files) {
if (!files.length) {
fileList.innerHTML = "<p>No files selected!</p>";
} else {
var list = document.createElement("ul");
for (var i = 0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var img = document.createElement("img");
img.src = window.URL.createObjectURL(files[i]);
img.height = 60;
img.onload = function(e) {
window.URL.revokeObjectURL(this.src);
}
li.appendChild(img);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
fileList.appendChild(list);
}
}
</script>
HERE the Mozilla DOC.
HERE some problem to do that.