I'm asking users to upload and HTML file, I would like to convert the contents of the HTML file into a string.
HTML file:
<form action="">
<input type="file" name="pic" accept="html" id = "htmlFile">
</form>
JAVASCRIPT
function readTextFile(file) //this is all wrong I think
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
If I understand you correctly, you can read the file after the input change with FileReader like this:
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
alert( "Got the file.n"
+"name: " + f.name + "n"
+"type: " + f.type + "n"
+"size: " + f.size + " bytesn"
+ "contents:" + contents
);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('htmlFile').addEventListener('change', readSingleFile, false);
<form action="">
<input type="file" name="pic" accept="html" id="htmlFile">
</form>
Source
Related
This is the code, so here is code for multiple preview images. So I want to delete the selected image? So when you upload images you click on image and image disappeared but it's only hidden not deleted?
How I can fix this? Because I'm using .remove(); method but nothings happened, its just hidden image
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".selFile", removeFile);
});
var selDiv = "";
var storedFiles = [];
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
var device = $(e.target).data("device");
filesArr.forEach(function(f) {
if (!f.type.match("image.*")) {
return;
}
storedFiles.push(f);
var reader = new FileReader();
reader.onload = function(e) {
var html = "<div><img src=\"" + e.target.result + "\" data-file='" + f.name + "' class='selFile' title='Click to remove'>" + f.name + "<br clear=\"left\"/></div>";
$("#selectedFiles").append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var data = new FormData();
for (var i = 0, len = storedFiles.length; i < len; i++) {
data.append('files', storedFiles[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'handler.cfm', true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(e.currentTarget.responseText);
alert(e.currentTarget.responseText + ' items uploaded.');
}
}
xhr.send(data);
}
function removeFile(e) {
var file = $(this).data("file");
for (var i = 0; i < storedFiles.length; i++) {
if (storedFiles[i].name === file) {
storedFiles.splice(i, 1);
break;
}
}
$(this).parent().remove();
}
This is my simple HTML
<script src="aa.js"></script>
<form id="myForm">
<input type="file" id="files" name="files" multiple>
<div id="selectedFiles"></div>
<br/>
<input type="submit">
</form>
You need to reset the input value:
function removeFile(e) {
var file = $(this).data("file");
for (var i = 0; i < storedFiles.length; i++) {
if (storedFiles[i].name === file) {
storedFiles.splice(i, 1);
break;
}
}
$(this).parent().remove();
// add it here
jQuery("#files").val("");
}
<input type='file' name="image" onchange="preview(this);" multiple="multiple" />
window.preview = function (input){
if(input.files && input.files[0]) {
var reader = new FileReader();
reader.readAsDataURL(input.files[0]);
reader.onload = function(e){
$("#previewImg").append("<img src='" + e.target.result +"'>");
}
}
}
I have a function using file reader to preview image, It works fine in single file.
However I try to achieve multiple files.
My question is how to get input files array, loop files through file reader and append img
Javascript Solution Fiddle DEMO
<input id="files" type="file" multiple="multiple" />
<output id="result" />
Pure JavaScript:
function handleFileSelect(event) {
//Check File API support
if (window.File && window.FileList && window.FileReader) {
var files = event.target.files; //FileList object
var output = document.getElementById("result");
for (var i = 0; i < files.length; i++) {
var file = files[i];
//Only pics
if (!file.type.match('image')) continue;
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var div = document.createElement("div");
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" + "title='" + file.name + "'/>";
output.insertBefore(div, null);
});
//Read the image
picReader.readAsDataURL(file);
}
} else {
console.log("Your browser does not support File API");
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
jQuery Solution
jQuery File Input Image Preview Before It Is Uploaded
<form id="form1" runat="server">
<input type='file' id="inputFile" />
<img id="image_upload_preview" src="http://placehold.it/100x100" alt="your image" />
</form>
jQuery:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#image_upload_preview').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#inputFile").change(function () {
readURL(this);
});
Working Fiddle
Javascript
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function (theFile) {
return function (e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('previewImg').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
More details about Files API and reference help for this answer...
Using your code Working Fiddle
HTML
<input type='file' name="image" onchange="preview(this);" multiple="multiple" />
<div id='previewImg'></div>
Javascript
window.preview = function (input) {
if (input.files && input.files[0]) {
$(input.files).each(function () {
var reader = new FileReader();
reader.readAsDataURL(this);
reader.onload = function (e) {
$("#previewImg").append("<img class='thumb' src='" + e.target.result + "'>");
}
});
}
}
Muliple File previewing using Jquery and DataURL
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script language="Javascript">
$(function () {
$("#browse").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#preview");
dvPreview.html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height:100px;width: 100px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
</script>
</html>
my aswer i believe is easy. I need create a code to get base64 content in FileReader function to send to database. I try to put the base64 string and put in form type hidden but i cant do. I upload the source code bellow:
JSFIDDLE
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
alert(
"name: " + f.name + "n"
+ "starts with: " + contents.substr(1, contents.indexOf("n"))
);
document.write(f.name);
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
</script>
Try using the function from MDN which should also support unicode:
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
alert(
"name: " + f.name + "n"
+ "starts with: " + contents.substr(1, contents.indexOf("n"))
);
document.getElementById('b64').innerHTML = b64EncodeUnicode(contents);
};
})(f);
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
}
document.getElementById('fileinput').addEventListener('change',
readMultipleFiles, false);
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
Notes:
I tested the above using an ascii file and https://www.base64encode.org/
Removed the document.write. Instead the result is displayed in a span with id="b64" (document.getElementById('b64').innerHTML = ...)
As is, will work only for 1 file. Requires minor editing or putting back the document.write to support multiple files
Fiddle: https://jsfiddle.net/g6g1a51p/4/
I'm trying to use the SitePoint Drag and Drop file upload to upload images to my site. My cshtml page contains the form and the userID for the current user. I would like to rename the file to the userID, but AJAX asynchronously uploads the image without sending the userID data along. Therefore I can't rename the file. How can I pass the userID from the cshtml page to the php page, via JS/AJAX, to be able to rename the file?
Here is the cshtml:
<form id="upload" action="test2.php" method="POST" enctype="multipart/form-data">
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="fileselect[]" accept="image" />
<input type="text" id="id" name="id" value="#userID" hidden /> //This is referencing a SQL query to get the UserID
//It's the data I want to pass along
<div id="filedrag">or drop files here</div>
<script src="filedrag.js"></script>
Here is the PHP:
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
$userID = ???
if ($fn) {
$file_ext = substr($fn, strripos($fn, '.'));
$newfilename = $userID.$file_ext;
// AJAX call
file_put_contents(
'uploads/' . $newfilename,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
Here is the full JS:
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
UploadFile(f);
}
}
// output file information
function ParseFile(file) {
Output(
"<p>File information: <strong>" + file.name +
"</strong> type: <strong>" + file.type +
"</strong> size: <strong>" + file.size +
"</strong> bytes</p>"
);
// display an image
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" /></p>'
);
}
reader.readAsDataURL(file);
}
// display text
if (file.type.indexOf("text") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
Output(
"<p><strong>" + file.name + ":</strong></p><pre>" +
e.target.result.replace(/</g, "<").replace(/>/g, ">") +
"</pre>"
);
}
reader.readAsText(file);
}
}
// upload JPEG files
function UploadFile(file) {
// following line is not necessary: prevents running on SitePoint servers
if (location.host.indexOf("sitepointstatic") >= 0) return
var xhr = new XMLHttpRequest();
if (xhr.upload && file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) {
// create progress bar
var o = $id("progress");
var progress = o.appendChild(document.createElement("p"));
progress.appendChild(document.createTextNode("upload " + file.name));
// progress bar
xhr.upload.addEventListener("progress", function(e) {
var pc = parseInt(100 - (e.loaded / e.total * 100));
progress.style.backgroundPosition = pc + "% 0";
}, false);
// file received/failed
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4) {
progress.className = (xhr.status == 200 ? "success" : "failure");
}
};
// start upload
xhr.open("POST", $id("upload").action, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton");
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
I have this textarea:
<input id="inputOuvrirFichier" type="file" onchange="handleFiles(this.files)" name="files[]" accept=".txt">
I need to put the contents of a .txt file into this textarea.
This is my function :
function handleFiles(file){
document.getElementById("titre").click();
console.log(file);}
How can i get the text contain in the file please ? (Javascript)
Thanks.
JS, have not access to local on ur server, only throw ajax-request:
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
$('#inputOuvrirFichier').text(allText)
}
}
}
rawFile.send(null);
}
You may use the FileReader API
function handleFiles(files) {
var i = 0;
var reader = new FileReader();
reader.onload = function() {
i++;
document.getElementById('result').innerHTML += this.result;
if (i < files.length)
reader.readAsText(files[i])
};
reader.readAsText(files[0]);
}
<input id="inputOuvrirFichier" type="file" onchange="handleFiles(this.files)" name="files[]" accept=".txt" multiple="">
<div id="result"></div>