I have a button that uploads the excel file.
<input type="file" id="input-excel" value="Choose File" accept=".xlsx" />
Below is an embedded script in the HTML to read the excel file and display it in the UI.
<script type="text/javascript">
// read and display the records from excel file on the screen
// passing in my button id here
$('#input-excel').change(function (e) {
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onload = function (e) {
var excelData = new Uint8Array(reader.result);
var wb = XLSX.read(excelData, { type: 'array' });
console.log(wb);
var htmlstr = XLSX.write(wb, {/* sheet: "Sheet1",*/ type: 'binary', bookType: 'html'});
$('#wrapper')[0].innerHTML += htmlstr;
};
});
</script>
#section scripts{
<script src="~/Scripts/ViewModels/RmaCreation/rmacreation.js"></script>
<script src="~/Scripts/knockout-3.2.0.js"></script>
<script language="javascript" src="~/Scripts/xlsx.full.min.js"></script>
}
I am able to upload excel file in the first iteration. I can see the records from the excel file in the UI.
However, the button becomes unresponsive in the second iteration. How do I make this button responsive after every iteration?
https://jsfiddle.net/03ut9zjs/2/
<input type="file" id="input-excel" value="Choose File" accept=".xlsx" />
<div id="wrapper">
</div>
// read and display the records from excel file on the screen
// passing in my button id here
$('#input-excel').change(function (e) {
$('#wrapper')[0].innerHTML ="";
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onload = function (e) {
var excelData = new Uint8Array(reader.result);
var wb = XLSX.read(excelData, { type: 'array' });
console.log(wb);
var htmlstr = XLSX.write(wb, {/* sheet: "Sheet1",*/ type: 'binary', bookType: 'html'});
$('#wrapper')[0].innerHTML += htmlstr;
};
});
You haven't included wrapper div in your code so i am not sure where/how you've placed it.
It seems to work fine in this fiddle. Are you able to recreate the issue here?
Related
I want to transform my image into base64 and then into JSON to send it via a post request to a server in java script.
I have looked for several solutions on the internet but none of them really work. Can someone explain to me the logic to have to achieve the code?
For now, I have this code:
JS code :
<script>
function convert (){
//image = btoa(URL="../static/images/images_final.jpg");
fetch("/predict" ,{
method: "POST",
body: JSON.stringify({result})
})
}
var file = window.document.querySelector('#form-base64-converter-encode-image-file').files[0];
getBase64(file);
const fileInput = document.getElementById("fileInput");
fileInput.addEventListener("change", e => {
const file = fileInput.files[0];
const reader = new FileReader();
reader.addEventListener("load", () => {
console.log(reader.result);
});
reader.readAsDataURL(file);
});
</script>
htlm code :
<form>
<input type="file" id="fileInput">
<button class="button"
type="reset"
onClick="convert()">
<h4>ENVOYER </h4>
</button>
</form>
API flask:
#app.post("/predict")
def predict_image():
req = request.get_json(force=True)
b64Image = req["image"]
buf = base64.b64decode(b64Image)
return print(b64Image[:20], buf[:20])
I want to read a local binary file. So, I do this
var file = new File([""], url);
var reader = new FileReader();
reader.onload = function () {
parse(reader.result);
}
reader.readAsArrayBuffer(file);
where url is a filepath like url="c:\temp\myfile.bin"
I don't have any errors, but something is wrong, because all data from my app disappear. What could be wrong ? Any ideas ?
Thanks!
I guess you have to use input type="file" for security reasons.
Here's a working example. For convenience it shows the opened file in the same browser window.
<html>
<body>
<script>
function readFile() {
var reader = new FileReader();
file = document.getElementById("uploadText").files[0];
reader.onload = function (ev) {
document.getElementById("obj").data = ev.target.result;
// parse(ev.target.result);
};
reader.readAsDataURL(file);
// reader.readAsArrayBuffer(file);
};
</script>
<div>
<input id="uploadText" type="file" onchange="readFile();" />
</div>
<object id="obj" data="" />
</body>
</html>
I have this in my html page:
<input type="file" id="fileInput" />
and this in my javascript page:
window.onload = function () {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function (e) {
// code that handles reading the text file
var file = fileInput.files[0];
var textType = /text.*/;
// checks if the file is a text file
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!";
}
});
}
I want to be able to convert the Filereader into an array so I can do something like:
document.getElementById("today").innerHTML = today[0];
Is this possible? I also don't think this is the way to read a csv file using filereader.
UPDATE: I have figured out how to get the csv file and turn it into an array by the following code:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "data.csv",
dataType: "text",
success: function (data) { processData(data); }
});
function processData(csv) {
var temp = new Array();
temp = csv.split(",");
document.getElementById("today").innerHTML = temp[0];
}
});
Now I am wondering if there is a way to use FileReader() so I can select the file from the html page instead of using url: "data.csv" so I can select multiple files.
You can handle this a few ways. You might think to ajax the file to a PHP script, then do something like $csvData[] = fgetcsv($file). Then you can echo json_encode($csvData);. It may be an extra http/server request but processing files is much easier.
There are some Javascript libraries that you wouldn't need to run server-side scripts for - JQuery CSV and PapaParse
New to javascript, having trouble figuring this out, help!
I am trying to use the Javascript FileReader API to read files to upload to a server. So far, it works great for text files.
When I try to upload binary files, such as image/.doc, the files seem to be corrupted, and do not open.
Using dojo on the client side, and java on the server side, with dwr to handle remote method calls. Code :
Using a html file input, so a user can select multiple files to upload at once :
<input type="file" id="fileInput" multiple>
And the javascript code which reads the file content:
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
// fileContent object contains the content of the read file
};
})(this.filesToBeUploaded[i]);
reader.readAsBinaryString(this.filesToBeUploaded[i]);
}
}
The fileContent object will be sent as a parameter to a java method, which will write the file.
public boolean uploadFile(String fileName, String fileContent) {
try {
File file = new File("/home/user/files/" + fileName);
FileOutputStream outputStream = new FileOutputStream(file);
outputStream.write(fileContent.getBytes());
outputStream.close();
} catch (FileNotFoundException ex) {
logger.error("Error uploading files: ", ex);
return false;
} catch (IOException ioe) {
logger.error("Error uploading files: ", ioe);
return false;
}
return true;
}
I have read some answers suggesting the use of xhr and servlets to achieve this.
Is there a way to use FileReader, so that it can read files of any type (text, image, excel etc.) ?
I have tried using reader.readAsBinaryString() and reader.readAsDataUrl() (Decoded the base64 fileContent before writing to a file), but they did not seem to work.
PS :
1. Also tried reader.readAsArrayBuffer(), the resultant ArrayBuffer object shows some byteLength, but no content, and when this is passed to the server, all I see is {}.
This bit of code is intended to work on only newer versions of browsers..
Thanks N.M! So, it looks like ArrayBuffer objects cannot be used directly, and a DataView must be created in order to use them. Below is what worked -
uploadFiles: function(eve) {
var fileContent = null;
for(var i = 0; i < this.filesToBeUploaded.length; i++){
var reader = new FileReader();
reader.onload = (function(fileToBeUploaded) {
return function(e) {
fileContent = e.target.result;
var int8View = new Int8Array(fileContent);
// now int8View object has the content of the read file!
};
})(this.filesToBeUploaded[i]);
reader.readAsArrayBuffer(this.filesToBeUploaded[i]);
}
}
Refer N.M 's comments to the question for links to the relevant pages.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays
example
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>
<body>
<script>
function PreviewImage() {
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("uploadImage").files[0]);
oFReader.onload = function (oFREvent) {
var sizef = document.getElementById('uploadImage').files[0].size;
document.getElementById("uploadPreview").src = oFREvent.target.result;
document.getElementById("uploadImageValue").value = oFREvent.target.result;
};
};
jQuery(document).ready(function(){
$('#viewSource').click(function ()
{
var imgUrl = $('#uploadImageValue').val();
alert(imgUrl);
//here ajax
});
});
</script>
<div>
<input type="hidden" id="uploadImageValue" name="uploadImageValue" value="" />
<img id="uploadPreview" style="width: 150px; height: 150px;" /><br />
<input id="uploadImage" style="width:120px" type="file" size="10" accept="image/jpeg,image/gif, image/png" name="myPhoto" onchange="PreviewImage();" />
</div>
Source file
</body>
</html>
I'm trying to get image as Object of javascript on the client side to send it using jQuery
<html>
<body>
<script language="JavaScript">
function checkSize()
{
im = new Image();
im.src = document.Upload.submitfile.value;
if(!im.src)
im.src = document.getElementById('submitfile').value;
alert(im.src);
alert(im.width);
alert(im.height);
alert(im.fileSize);
}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
<p>Filename: <input type="file" name="submitfile" id="submitfile" />
<input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>
But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?
The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.
var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
var width;
var height;
var fileSize;
var reader = new FileReader();
reader.onload = function(event) {
var dataUri = event.target.result,
img = document.createElement("img");
img.src = dataUri;
width = img.width;
height = img.height;
fileSize = imgFile.files[0].size;
alert(width);
alert(height);
alert(fileSize);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
reader.readAsDataURL(imgFile.files[0]);
}
I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.
This is what I use and it works great for me. I save the image as a blob in mysql. When clicked, the file upload dialog appears, that is why i set the file input visibility to hidden and set its type to upload image files. Once the image is selected, it replaces the existing one, then I use the jquery post method to update the image in the database.
<div>
<div><img id="logo" class="img-polaroid" alt="Logo" src="' . $row['logo'] . '" title="Click to change the logo" width="128">
<input style="visibility:hidden;" id="logoupload" type="file" accept="image/* ">
</div>
$('img#logo').click(function(){
$('#logoupload').trigger('click');
$('#logoupload').change(function(e){
var reader = new FileReader(),
files = e.dataTransfer ? e.dataTransfer.files : e.target.files,
i = 0;
reader.onload = onFileLoad;
while (files[i]) reader.readAsDataURL(files[i++]);
});
function onFileLoad(e) {
var data = e.target.result;
$('img#logo').attr("src",data);
//Upload the image to the database
//Save data on keydown
$.post('test.php',{data:$('img#logo').attr("src")},function(){
});
}
});
$('#imagess').change(function(){
var total_images=$('#total_images').val();
var candidateimage=document.getElementById('imagess').value;
formdata = false;
var demo=document.getElementById("imagess").files;
if (window.FormData) {
formdata = new FormData();
}
var i = 0, len = demo.length, img, reader, file;
for ( ; i < len; i++ ) {
file = demo[i];
if (file.type.match(/image.*/)) {
if (formdata) {
formdata.append("images", file);
}
}
}
$('#preview').html('Uploading...');
var url=SITEURL+"users/image_upload/"+total_images;
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
$('#preview').html('');
if (res == "maxlimit") {
alert("You can't upload more than 4 images");
}
else if (res == "error") {
alert("Image can't upload please try again.")
}
else {
$('#user_images').append(res);
}
}
});
});