I am using the File API to upload a file and save its content as a variable in JavaScript. This is what I have so far but, the result that I get is undefined.
<body>
<input type="file" id="file" name="file" multiple />
<script>
function handleFileSelect(evt) {
// grab the file that was uploaded which is type File.
// evt is the event that was triggered
// evt.target returns the element that triggered the event
// evt.target.files[0] returns the file that was uploaded
var file = evt.target.files[0];
// instantiate a FileReader object to read/save the file that was uploaded
var reader = new FileReader();
// read the file and save as an array
fileArray = reader.readAsArrayBuffer(file);
window.alert("hello");
window.alert(fileArray);
}
document.getElementById('file').addEventListener('change', handleFileSelect, false);
</script>
FileReader is asynchronous. you should set up onload
var reader = new FileReader();
reader.onload = function(){
console.log(reader.result);
};
// read the file and save as an array
reader.readAsArrayBuffer(file);
Related
I need to load a file on the OnLoad event. I need to get the file path using the javascript Prompt and load the file, presenting the content in a DIV.
My problem is in the file loading. I cant use the window manager to choose the file name.
Here is how you upload a file. Then where it console.logs(res) you can do any logic you want with the data from the file.
/* Native JS
*/
const readFile = (event) => {
//First File Upload
let file = event.target.files[0];
if (file) {
//reading File from User Input*
new Promise((resolve, reject) => {
//Reading Txt File
let reader = new FileReader();
//Resolving On read
reader.onload = (evt) => {
resolve(evt.target.result);
};
reader.readAsText(file);
//reading file as txt*
reader.onerror = reject;
})
//Read data
.then(console.log(res))
//Catching Errors
.catch((err) => {
console.log(err)
});
}
}
document.getElementById('file').addEventListener('change', readFile, false);
<div class="ui icon header">
<i class="pdf file outline icon"></i>
Upload Text Document Below
<input type="file" accept="text/*" id="file" class="ui blue button">
</div>
I want to take a user uploaded a file in Javascript and extract data from it without submitting the page and process that data for giving other options in the form on the same page.
It would be of great help if anyone could please help me out here.
Use the HTML 5 file API and FileReader, it allows you to work with files directly on the browser.
Here's a full example:
<input type="file" id="input" onchange="handleFiles(this.files)">
<div id="output">
</div>
<script type="text/javascript">
function handleFiles(files) {
//$("#output").html("got: "+files[0].name);
var reader = new FileReader();
reader.onload = function(e) {
$("#output").html(reader.result);
}
reader.readAsText(files[0]);
}
</script>
Please read this: https://developer.mozilla.org/en-US/docs/Web/API/File/Using_files_from_web_applications
and read this:
https://www.w3.org/TR/FileAPI/#APIASynch
The FileReader class provides the following useful methods:
interface FileReader: EventTarget {
// async read methods
void readAsArrayBuffer(Blob blob);
void readAsBinaryString(Blob blob);
void readAsText(Blob blob, optional DOMString label);
void readAsDataURL(Blob blob);
....
Please read the above links, they will provide all the examples for you.
Here is the example of how to access a file's content.
function handleFileSelect(evt) {
var files = evt.target.files;
var f = files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
// Do everything what you need with the file's content(e.target.result)
console.log(e.target.result);
};
})(f);
reader.readAsText(f);
}
document
.getElementById("upload")
.addEventListener("change", handleFileSelect, false);
I have a function that sends data through data:JSON.stringify(formdata)using POST to a remove .NET webservice. I have no problem this far. What I want to do it to add also add a another value to the formdata JSON that will hold a base64 image data and send it to the server, and there I will convert it back to a JPEG image.
How can I so that? I already have a preview function that created a preview, but also create a base64 image:
function previewFile() {
var preview = document.querySelector('.uploadimage');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
I see many question people asking how to upload image to the server. I want to stay with the current configuration but just pass the base64 image data to the server as a string. I see many developers struggling with that, and most of them just engine up creating a form in javascript and submitting like that.
Here is a recent way I did this:
string base64 = base64string.Substring(base64string.IndexOf(',') + 1);
byte[] imageData = Convert.FromBase64String(base64);
Image img;
using (var ms = new MemoryStream(imageData, 0, imageData.Length)) {
img = Image.FromStream(ms, true);
You will need:
using System.Drawing;
OR to simply convert to a jpg, use this:
File.WriteAllBytes("image.jpeg", Convert.FromBase64String(base64));
For sending the data I use the following JS:
function sendImage() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.onload = function (e) {
$("#imgImage").attr("src", e.target.result); //show a preview
//send e.target.result as a string to your webservice
};
FR.readAsDataURL(this.files[0]);
}
}
I use this event to listen for uploaded files:
document.getElementById("fileid").addEventListener("change", sendImage, false);
And the front end:
<input type="file" id="fileid" />
I allow the user to select a mp3 file from the local file System and then
allow to download the same file. Its for learning purpose.
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
var fReader = new FileReader();
fReader.onload = function(ev) { //onload event
var dataUrl = ev.target.result;
var downloadCon = document.querySelector('#download')
downloadCon.href = dataUrl;
};
fReader.readAsDataURL(file); //start reading the file
}
});
}
</script>
The HTML body:
<body>
<div class="controls">
<input type="file" id="musicFile">
<a id='download'href='#' download='music.mp3' class='downloadLink'>
Download File
</a>
</div>
</body>
When I click the Download File, nothing happens. Can you tell me what am I doing wrong?
You don't need to use FileReader to do that. Simply, you need to create a URLObject and make the A tag to point to it. The code for that (tested under Chrome and Firefox for Linux):
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
document.getElementById( 'download' ).href = URL.createObjectURL(file);
}
});
}
</script>
To be more specific at what I did in your code - I removed all the FileReader code and added
document.getElementById( 'download' ).href = URL.createObjectURL(file);
in it's place. I didn't touch your HTML.
Hope that helps.
I am trying to use the readAsDataURL function for a javascript FileReader in order to retrieve data from an html form to upload it into a database. I currently have a file Object from the form but cannot get it into a form to put into a database.
HTML
input type="file" style="width: 300px" id="costumePicUpload" multiple
button type="submit" onclick="submitForm()">SUBMIT</button
JavaScript
function submitForm(){
var file = document.getElementById("costumePicUpload").files[0];
var reader = new FileReader();
var img;
reader.onloadend = function(e) {
img = new Image();
img.src = e.target.result;
if(e.target.error){
alert(e.target.error.code);
}
};
reader.readAsDataURL(file);
};
}
When I output the link in an alert it just says undefined. Does anyone know how I can fix this?
UPDATE
I was able to get a FileError.NOT_READABLE_ERR but have no idea what could be causing this.
I faced the same problem here is code
Html code
<input type="file" name="costumePicUpload" id="costumePicUpload" onChange="viewImage(this)" >
<img src="#" id="imageThumb">
Javascript Function
function viewImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#imageThumb').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
When we choose the image file to upload it will read image using file reader and set it as a source for another image with id "imageThumb".