I have a web page with file upload controller an image.
<img src='#' id='imageId' alt='your image' height='64' width='64' src='placeholder.png' class='placeholder' >
<input type='file' id='myID' onchange='previewImage(this)' accept='image/*' data-thumbnail='imageId'>
Actually above HTML code is derived from my asp code.
Ok..Now what I want to do is generate these two components with manual coding.So I start like this.
System.Web.UI.WebControls.Image preview = new System.Web.UI.WebControls.Image();
preview.ID = "imageId";
preview.Height = 64;
preview.Width = 64;
FileUpload tt = new FileUpload();
tt.ID = "myID";
But there are some attributes remaining in the original HTML code.I do not know exactly how to implement them with C# code.
Further for the "onchange" event of the File upload control have to be implemented."previewImage(this)" is javascript function which I used to preview the selected image.
Sp please help me to solve these things with c# code.
Try this,
tt.Attributes.Add("onchange", "previewImage()");
May this help you:
tt.Attributes["onchange"] = "previewImage(this)";
I think this may help you...
javascript
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<script type="text/javascript">
function previewImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageId').attr('src', e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}
</script>
<img src='#' id='imageId' alt='your image' height='64' width='64' class='placeholder' >
<input type='file' id='myID' onchange='previewImage(this)' >
to call this function in c#
ScriptManager.RegisterStartupScript(this, this.GetType(), "Javascript", "javascript:previewImage(input); ", true);
Related
So, I've been working on a page that uses only local files (server is not an option, unfortunately. Not even a localhost. The struggle is real.) and I've come to a situation where I need to grab text from a .csv file and populate it to the page. I have this bit of code that works, but I need to have a file set within the function when a button is pressed. Looking up the file manually isn't an option (to visualize what I'm doing, I'm making a mock database file in the most annoying way possible (because I have to, not because I want to)).
In the page I would have something like:
<button id="myButton" onclick="getText()"></button>
<script>
var myFile = "dataset.csv";
...
</script>
The following bit of code works (in regards to having it pull the data from the csv file), but, as I said, I need to pull the text from the file when a button is pressed and just have the file name set in the script, not pulling it up manually.
<!DOCTYPE html>
<html>
<body>
<input type="file" id="fileinput" />
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
From what I can tell from the API, I would need to set the file attributes to a blob in order to pass it to FileReader. How I can do this without using an input box, I have no idea. There's also a 50% chance that I am completely wrong about this since I obviously don't know how to get this done.
If someone could show me how to achieve this with regards to what I'm looking for, it would be very much appreciated. I'm absolutely stumped.
Thank you.
Note: CORS restrictons will prevent this from working in most browsers. You can use FireFox Developer Edition, which disables CORS validation.
You can use an XMLHttpRequest to load a local file:
<!DOCTYPE html>
<html>
<body>
<button onclick="readSingleFile()">Click Me</button>
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile() {
let xhr = new XMLHttpRequest();
let url = "relative/path/to/file.txt;
if (!url) return;
xhr.onload = dataLoaded;
xhr.onerror = _ => "There was an error loading the file.";
xhr.overrideMimeType("text/plain");
xhr.open("GET",url);
xhr.send();
}
function dataLoaded(e){
var contents = e.target.responseText;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
</script>
</body>
</html>
currently i am choosing a file and converting to base64 string and displaying in html page.see the below code.
But i want in such a way that while loading the function it will automatically fetch the file from the location where the image saved and convert to base64 and display. I just want to skip the manual way of choosing..please help
<html>
<body>
Choose File: <input id="imageToLoad" type="file" onchange="displayImage();" />
<p>Image encoded</p>
<textarea id="base64TextArea" style="width:550;height:240" ></textarea>
<img id="myImg" width="218" height="300" src="" />
<script type="text/javascript">
function displayImage()
{
var filesSelected = document.getElementById("imageToLoad").files;
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
base64TextArea.innerHTML = fileLoadedEvent.target.result;
document.getElementById("myImg").src = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(fileToLoad);
}
}
</script>
</body>
</html>
You can't fetch arbitrary files on a client's computer with JS. Using most browsers, the client must manually choose a file to be processed by the script.
If you think about it, it would be a major security flaw if any website could access any file on your computer.
I'm not sure why Base64 is an important aspect here. Please give some details if converting the image to text is a specific requirement of your needs, but if you only want to display and reference the image, you can start with this:
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
document.getElementById("myImg").src = URL.createObjectURL(fileToLoad);
}
This will use an "object URL" which is a shorthand way of referring to a file that has been drag/dropped, or picked from an <input>
I want to be able to open files through input type="file" in chrome apps.
The following code produce an error:
Refused to execute inline event handler because it violates the
following Content Security Policy directive
<html>
<head>
<title></title>
</head>
<body>
<input type="file" onchange="btnClick(event)" />
<script>
function btnClick(evt) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
var str = event.target.result;
console.log(str);
}
fileReader.readAsText(event.target.files[0]);
}
</script>
</body>
</html>
What can I do to fix it?
Inline event handlers dont work in chrome apps, remove event handler from the html and implement it in javascript. Also, the script must not be in the html file. it should be in its own js file and referenced in the html. This is documented HERE
html
<input type="file" id="file1"/>
js
document.getElementById("file1").addEventListener("change",handleChange);
function handleChange(){
var fileReader = new FileReader();
fileReader.onload = function (event) {
var str = event.target.result;
console.log(str);
}
fileReader.readAsText(event.target.files[0]);
}
FIDDLE
How to read text from a txt file with one button to browse the file and other button to display text. Pls help me in getting the code. i have tried many codes but othing worked. some code was like this. Thanks in advance
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "#":
output=output.split("\n").filter(/./.test, /\#/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Dont think this line is working properly:
output=output.split("\n").filter(/./.test, /\#/).join("\n");
Try changing it to:
output=output.split("\n").filter(function(l) {
//return /^\#/.test(l); // Starting with #
return l.indexOf('#') > -1; // Containing #
}).join("\n");
It would be interesting to see if this would work as well:
output=output.split("\n").filter(/\#/.test.bind(/\#/)).join("\n");
The second arguments passed to the .filter method is the context:
array.filter(callback[, thisObject])
Get the input file, use FileReader() to read it,on file load get text that matches the pattern. Finally display it through "main" div. Should work..
HTML :
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery :
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\#/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
Demo
I've tried use javascript to open text file and get his name and his content, so right now I'm stuck at string, because I used input - type file to get directory / path.
Anyway, my question what is wrong in the next code, and how can i get text file content using javascript?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Display Text Files</title>
<script type="text/javascript">
var str = document.getElementById('txt').value;
function display() {
if (str != "") {
var filename = str.split("/").pop();
document.getElementById('filename').innerHTML = filename;
}
}
</script>
</head>
<body>
<form method="get" action="#" >
<input type="file" accept="text/plain" id="txt" />
<input type="submit" value="Display Text File" onclick="display();" />
</form>
</body>
</html>
EDIT: I also wanna disable in input file the all files opition (*) to text files only (.txt).
Thanks!
Modern browsers implementing FileReader can do this. To test your browser check if window.FileReader is defined.
Here is some code I wrote only this morning to do just this. In my case I simply drag a file onto the HTML element which is here referenced as panel.in1 but you can also use <input type="file" /> (see the reference below).
if (window.FileReader) {
function dragEvent (ev) {
ev.stopPropagation ();
ev.preventDefault ();
if (ev.type == 'drop') {
var reader = new FileReader ();
reader.onloadend = function (ev) { panel.in1.value += this.result; };
reader.readAsText (ev.dataTransfer.files[0]);
}
}
panel.in1.addEventListener ('dragenter', dragEvent, false);
panel.in1.addEventListener ('dragover', dragEvent, false);
panel.in1.addEventListener ('drop', dragEvent, false);
}
It is the reader.onloadend function which gets the text of the file which you recover in the event handler as this.result.
I got most of the mechanism on how to do this from MDN : https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications