How to get XML file content in React? [duplicate] - javascript

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?

I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>

Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}

Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

Related

Upload multiple files parallel in azure blob with SAS Token in javascript

I am trying to upload multiple video files in azure blob storage with the help of SAS token.
As you can see in this image :- Image
By looking in the console It looks like browser is handling the file and uploading it by chunks. So I didn't implemented it in my code. Don't know if that's the right way.
Files are uploading successfully but its taking lot of time.
<div class="container">
<div class="row">
<div class="form-group">
<label for="Files"></label>
<input type="file" id="fileControl" multiple />
<br />
<span class="" id="SizeLimitSAS" style="visibility: hidden; font-size:small"></span>
<br />
<progress id="uploadProgress" class="form-control" value="0" max="100" style="height: 60px;"></progress>
<br />
</div>
<div class="form-group">
<input type="button" id="btnUpload" value="Upload files" />
</div>
<br />
<br />
<span class="" id="countOfFileUploaded" style="visibility: hidden; font-size:large"></span>
</div>
</div>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", init, false);
function init() {
document.querySelector('#fileControl').addEventListener('change', handleFileSelect, false);
sizeLimit = document.querySelector("#SizeLimitSAS");
}
function handleFileSelect(e) {
if (!e.target.files) return;
var totalSize = 0;
sizeLimit.innerHTML = "";
var files = e.target.files;
for (var i = 0; i < files.length; i++) {
var f = files[i];
totalSize += f.size;
}
console.log(files)
console.log(totalSize)
sizeLimit.innerHTML += "</br>" + niceBytes(totalSize);
SizeLimitSAS.style.visibility = "visible";
}
const units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
function niceBytes(x) {
let l = 0, n = parseInt(x, 10) || 0;
while (n >= 1024 && ++l) {
n = n / 1024;
}
return (n.toFixed(n < 10 && l > 0 ? 1 : 0) + ' ' + units[l]);
}
var count = 0;
function upload(file, type, url) {
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function (aEvt) {
console.log(ajaxRequest.readyState);
if (ajaxRequest.readyState == 4)
console.log(ajaxRequest.responseText);
};
ajaxRequest.upload.onprogress = function (e) {
var percentComplete = (e.loaded / e.total) * 100;
console.log(percentComplete + "% completed");
if (percentComplete === 100) {
count++;
countOfFileUploaded.innerHTML = count + " file uploaded";
countOfFileUploaded.style.visibility = "visible";
}
uploadProgress.value = percentComplete;
};
ajaxRequest.onerror = function (jqXHR, exception, errorThrown) {
alert(jqXHR.status + "--" + exception + "--" + errorThrown);
};
ajaxRequest.open('PUT', url, true);
ajaxRequest.setRequestHeader('Content-Type', type);
ajaxRequest.setRequestHeader('x-ms-blob-type', 'BlockBlob');
ajaxRequest.send(file);
}
jQuery("#btnUpload").click(function () {
var files = fileControl.files;
for (var i = 0, file; file = files[i]; i++) {
upload(file, file.type, "https://container.blob.core.windows.net/videos/" + file.name + "?sp=racwdli&st=2023-01-18T12:51:14Z&se=2023-01-21T20:51:14Z&sv=2021-06-08&sr=c&sig=gfgkkbhbkekhbkigyyuvuuQB2XR1ynaSOQ%3D");
}
});
</script>
I tried in my environment and successfully uploaded file parallelly in Azure blob storage using browser.
You can use the below code to upload file parallely with SAS url:
Index.html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<button id="select-button">Select and upload files</button>
<input type="file" id="file-input" multiple style="display: none;" />
<div id="showProgress"></div>
<p><b>Status:</b></p>
<p id="status" style="height:300px; width: 593px; overflow: scroll;" />
</body>
<script type="module" src="index.js"></script>
</html>
Index.js
const { BlobServiceClient } = require("#azure/storage-blob");
const selectButton = document.getElementById("select-button");
const fileInput = document.getElementById("file-input");
const status = document.getElementById("status");
const reportStatus = message => {
status.innerHTML += `${message}<br/>`;
status.scrollTop = status.scrollHeight;
}
const blobSasUrl = "<blob sas url>";
const blobServiceClient = new BlobServiceClient(blobSasUrl);
const containerName = "test";
const containerClient = blobServiceClient.getContainerClient(containerName);
const uploadFiles = async () => {
try {
reportStatus("Uploading files...");
const promises = [];
for (var fileIndex = 0; fileIndex < fileInput.files.length; fileIndex++) {
const file = fileInput.files[fileIndex];
const blockBlobClient = containerClient.getBlockBlobClient(file.name);
document.getElementById('showProgress').innerHTML += file.name +":<div id='progress-"+ file.name +"'></div>"
var blobUploadOptions = {
blockSize: 4 * 1024 * 1024, // 4MB block size
parallelism: 20, // 20 concurrency
metadata: { 'testindex': fileIndex.toString() },
progress: function (ev) {
var percentdone = ((ev.loadedBytes / file.size) * 100);
var progessItem = document.getElementById('progress-' + file.name);
progessItem.innerHTML = percentdone.toFixed(2) + "%";
}
};
var promise=blockBlobClient.uploadBrowserData(file,blobUploadOptions);
promise.then((result)=>{
var progessItem = document.getElementById('progress-' + file.name);
progessItem.innerHTML += " file link"
});
promises.push(promise);
}
await Promise.all(promises);
alert("Done.");
}
catch (error) {
alert(error.message);
}
}
selectButton.addEventListener("click", () => fileInput.click());
fileInput.addEventListener("change", uploadFiles);
Console:
Browser:
Portal:
Reference:
Quickstart: Azure Blob storage library v12 - JS Browser - Azure Storage | Microsoft Learn

JavaScript, csv to json, split is not a function [duplicate]

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

what's wrong with these code? why it not sort preview image upload?

Here is the full code for html5 multiple upload file with removeable and preview image
but I don't know in function handleFileSelect(e) why it show the preview images with wrong sorting when choose more than 2 files? (Although, it upload to my folder correctly sort but I still want it to show preview with correct sorting)
<!doctype html>
<html>
<head>
<title>Proper Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<style>
#selectedFiles img {
max-width: 200px;
max-height: 200px;
float: left;
margin-bottom:10px;
}
.delete_img{
cursor:pointer;
color:red;
font-size:14px;
margin-left:10px;
}
</style>
</head>
<body>
<form id="myForm" method="post">
Username: <input type="text" name="username" id="username"><br/>
Email: <input type="text" name="email" id="email"><br/>
Multiple Files: <input type="file" id="files" name="files[]" multiple><br/>
<div id="selectedFiles"></div>
<input type="submit">
</form>
<script>
var selDiv = "";
var storedFiles = [];
$(document).ready(function() {
$("#files").on("change", handleFileSelect);
selDiv = $("#selectedFiles");
$("#myForm").on("submit", handleForm);
$("body").on("click", ".delete_img", removeFile);
});
function handleFileSelect(e) {
var files = e.target.files;
var filesArr = Array.prototype.slice.call(files);
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'> <span class='delete_img'> DEL </span><br>" + f.name + "<br clear=\"left\"/></div>";
selDiv.append(html);
}
reader.readAsDataURL(f);
});
}
function handleForm(e) {
e.preventDefault();
var username = document.getElementById('username').value; //get value จาก form input
var email = document.getElementById('email').value;
var data = new FormData();
data.append('username', username); //มาใส่ในajax object formdata เพื่อเตรียมส่งเข้าฝั่งserver
data.append('email', email);
for(var i=0, len=storedFiles.length; i<len; i++) {
data.append('files[]', storedFiles[i]); //อย่าลืม []
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'upload.php', true);
xhr.onload = function(e) {
if(this.status == 200) {
console.log(e.currentTarget.responseText);
//alert(e.currentTarget.responseText + ' items uploaded.');
window.location = "http://www.google.com";
}
}
xhr.send(data);
}
function removeFile(e) {
var img = e.target.parentElement.querySelector("img")
var file = img.getAttribute('data-file');
for(var i=0;i<storedFiles.length;i++) {
if(storedFiles[i].name === file) {
storedFiles.splice(i,1);
break;
}
}
$(this).parent().remove();
}
</script>
</body>
</html>
Maybe the total upload size of your files overcomes the max_upload_limit.Usually is 2 MB.As i tested your code in liveweave i don't have problem (5 images).Check the total size of your files. How much is it?

Reading uploaded text file contents in html

I want to show contents of uploaded file in html, I can just upload a text file.
My example.html:
<html xmlns="http://www.w3.org/1999/xhtml" >
<p>
Please specify a file, or a set of files:<br>
<input type="file" name="datafile" size="40">
</p>
<textarea id="2" name="y" style="width:400px;height:150px;"></textarea>
</html>
How can I show contents of any uploaded text file in textarea shown below?
I've came here from google and was surprised to see no working example.
You can read files with FileReader API with good cross-browser support.
const reader = new FileReader()
reader.onload = event => console.log(event.target.result) // desired file content
reader.onerror = error => reject(error)
reader.readAsText(file) // you could also read images and other binaries
See fully working example below.
document.getElementById('input-file')
.addEventListener('change', getFile)
function getFile(event) {
const input = event.target
if ('files' in input && input.files.length > 0) {
placeFileContent(
document.getElementById('content-target'),
input.files[0])
}
}
function placeFileContent(target, file) {
readFileContent(file).then(content => {
target.value = content
}).catch(error => console.log(error))
}
function readFileContent(file) {
const reader = new FileReader()
return new Promise((resolve, reject) => {
reader.onload = event => resolve(event.target.result)
reader.onerror = error => reject(error)
reader.readAsText(file)
})
}
label {
cursor: pointer;
}
textarea {
width: 400px;
height: 150px;
}
<div>
<label for="input-file">Specify a file:</label><br>
<input type="file" id="input-file">
</div>
<textarea id="content-target"></textarea>
Here's one way:
HTML
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button><td>
</tr>
JavaScript
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
Try this.
HTML
<p>
Please specify a file, or a set of files:<br>
<input type="file" id="myFile" multiple size="50" onchange="myFunction()">
</p>
<textarea id="demo" style="width:400px;height:150px;"></textarea>
JS
function myFunction(){
var x = document.getElementById("myFile");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
txt += (i+1) + ". file";
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes ";
}
}
}
}
else {
if (x.value == "") {
txt += "Select one or more files.";
} else {
txt += "The files property is not supported by your browser!";
txt += "The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
document.getElementById("demo").innerHTML = txt;
}
Demo

trying to leverage JSZip to open and then parse a specific file in a .zip

Have been trying to use the JSZip library to cycle through files in a .zip, looking for one (here, test.txt) that I want to parse for content.
Have attempted to do a modification of the sample [recommend viewing source on that] that JSZip provides:
<!DOCTYPE HTML>
<html>
<head>
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<div class = "container">
<div class = "hero-unit">
<input type="file" class="span7" id="input" name="file" multiple /> <!-- redo this in a bootstrappy way-->
<br>
<output id="output"></output>
</div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="/js/jszip-load.js"></script>
<script src="/js/jszip.js"></script>
<script src="/js/jszip-inflate.js"></script>
<script>
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('The File APIs are not fully supported in this browser.');
}
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
if (f.type !== "application/zip") {
document.getElementById('output').innerHTML = "<p class='text-error'>" + f.name + " isn't a zip file.</div>";
continue;
}
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
var zip = new JSZip(e.target.result)
$.each(zip.files, function (index, zipEntry) {
if (zipEntry.name == "test.txt"){
var text = zipEntry.asText();
var lines = text.split(/[\r\n]+/g); // tolerate both Windows and Unix linebreaks
for(var i = 0; i < lines.length; i++) {
if (lines[i].length > 240){
output.push('<li>' + lines[i] + '<br>');
}
}
document.getElementById('output').innerHTML = '<h2>Paths with more than 240 characters:</h2> <br><ol>' + output.join('') + '</ol>';
else{
alert("file not found!")
}
}
});
}
})(f);
}
}
document.getElementById('input').addEventListener('change', handleFileSelect, false);
</script>
</body>
</html>
For some reason, I'm sure having to do with the way that I am using the closure, it is not actually parsing the .zip files in question. Any ideas what I might be doing wrong here?
I use this code and am able to get all file data. content variable has file content:
function loadSettingsFile(evt) {
var files = evt.target.files;
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
try {
var zip = new JSZip(e.target.result);
$.each(zip.files, function (index, zipEntry) {
var content = zipEntry.asText();
alert(content);
});
} catch(e) {
alert(e)
}
}
})(f);
// read the file !
// readAsArrayBuffer and readAsBinaryString both produce valid content for JSZip.
reader.readAsArrayBuffer(f);
// reader.readAsBinaryString(f);
}
}

Categories

Resources