replace XMLHttpRequest in javascript - javascript

I used to read my local files using XMLHttpRequest.
function getData(fileName)
{
var filePath = fileName;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", filePath, false);
xmlhttp.send(null);
var fileContent = xmlhttp.responseText;
var tempArr = csv2Arr(fileContent);
var returnLabelArr = tempArr[0].toString().split(',');
tempArr.shift();
var returnDataArr = tempArr;
return { 'dataArr' : returnDataArr, 'labelArr' : returnLabelArr };
}
fileName starts with "C://..." and my program works on browser with address "file:///...".
But, without "--allow-file-access-from-files" tag, my code doesn't work on Chrome. And also it doesn't work on IE and Firefox without changing some security options.
So, I tried to jquery API like this,
function getData(fileName)
{
var filePath = fileName;
var fileContent;
$.ajax({
type: "GET",
url: filePath
})
.done(function(data) {
alert(data);
fileContent = data;
});
var tempArr = csv2Arr(fileContent);
var returnLabelArr = tempArr[0].toString().split(',');
tempArr.shift();
var returnDataArr = tempArr;
return { 'dataArr' : returnDataArr, 'labelArr' : returnLabelArr };
}
The Problem also occurs. I think Same-origin policy prevents it.
Can anyone give me some suggestions for me to access local files without changing security options? Should I use some plug-ins to solve this?
Please let me know.
Thank you.

If you can use <input type="file"> to select files, then the solution is:
HTML:
<form action="">
<input type="file" id="file-input" multiple="multiple" accept="image/jpeg" />
</form>
JS:
var fileInput = document.querySelector('#file-input');
fileInput.addEventListener('change', function(event) {
var files = fileInput.files;
if (files.lenght == 0) {
return;
}
for(var i = 0; i < files.length; i++) {
readFile(files[i]);
}
fileInput.value = "";
}, false);
var readFile= function(file) {
var reader = new FileReader();
reader.onload = function(e) {
var dataUrl = e.target.result;
// now, load the data into some element
// if this is image, you can do this:
var image = new Image();
image.src = dataUrl;
document.body.appendChild(image);
};
reader.readAsDataURL(file);
};
Also, discover the FileReader API to find out, how you can use it otherwise, as it has more methods to read data.

Related

How can I use filereader to parse csv file and convert it into an array?

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

Urls in creating chrome extension tabs do not work

I am creating a chrome extension which access a api and parses the json feed to get data. One of the data is a link and I want the link to be opened in a new tab. I use chrome.create.tabs to do it. But instead of opening a tab with specified url it opens like this
chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie%22
Here is my popup.js
document.addEventListener('DOMContentLoaded', init);
function init(){
var elem = document.getElementById('Add');
elem.addEventListener('click',func);
}
function func(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.twitch.tv/kraken/search/streams?q=league%20of%20legends", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// innerText does not let the attacker inject HTML elements.
var qtpie=JSON.parse(xhr.responseText);
var display_name = JSON.stringify(qtpie.streams[0].channel.display_name);
var stream_status = JSON.stringify(qtpie.streams[0].channel.status);
var stream_url=JSON.stringify(qtpie.streams[0].channel.url);
var res = display_name+" : "+stream_status+"\n"+stream_url;
console.log(stream_url);
var a = document.createElement('a');
var linkText = document.createTextNode(res);
a.appendChild(linkText);
a.setAttribute('href', stream_url);
a.addEventListener('click', link_handler(stream_url));
document.getElementById("status").appendChild(a);
var magic=activateLinks();
// document.getElementById("status").innerText = res;
}
}
xhr.send();
}
function activateLinks()
{
var links = document.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
(function () {
var ln = links[i];
var location = ln.href;
ln.onclick = function () {
chrome.tabs.create({active: true, url: location});
};
})();
}
}
function link_handler(url)
{
// Only allow http and https URLs.
if (url.indexOf('http:') != 0 && url.indexOf('https:') != 0) {
return;
}
chrome.tabs.create({url: url});
}
Here stream_url is the variable that stores the parsed url from json.
here is the json from which it is parsed from
"video_banner":null,
"background":null,
"profile_banner":null,
"profile_banner_background_color":null,
"partner":true,
"url":"http://www.twitch.tv/imaqtpie",
"views":91792487
i want the new tab to open http://www.twitch.tv/imaqtpie instead of chrome-extension://app_id/%22http://www.twitch.tv/imaqtpie
. Thanks in advance. Btw using <base href="http://" target="_blank"> does not work.
So the problem is for the url. Your url is improper when using chrome.tabs.create, because %22 indicates the character " in ASCII Encoding Reference. You should strip it off in the url when you get the element in html. Glad it helps!

Inside javascript need to change value of a hidden input field

I have tried several things but its not working. Can someone help me to understan the problem with this code. This is a file upload script. I'm using it with codeigniter. My requirement is after user upload files(works right now) those file names should added to the hidden field.
<input type="hidden" name="extra_images" value="" />
<label for="deal_duration">Deal Extra Images</label>
<div id="uploads"></div>
<div class="dropzone" id="dropzone">Drop files here to upload</div>
<script type="text/javascript">
(function(){
var dropzone = document.getElementById('dropzone');
var uploads = new Array();
var hidden = document.getElementsByName('extra_images');
var displayUploads = function(data){
var uploads = document.getElementById('uploads'),
anchor,
x;
var errors = new Array();
for(x=0;x<data.length;x=x+1){
if((typeof(data[x].file) === 'undefined') && (typeof(data[x].error) != 'undefined'))
{
errors.push(data[x].error);
}
else
{
anchor = document.createElement('a');
anchor.href = 'http://localhost/project-cg/'+ data[x].file;
anchor.innerText = data[x].name;
anchor.target = '_blank';
uploads.appendChild(anchor);
uploads.push(data[x].data[x].name);
}
}
if(errors.length > 0){
alert(errors);
}
if(uploads.length > 0){
//This is what I tried so far.But its not working
hidden.value = uploads.join("|");
}
}
var upload = function(files){
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
for(x=0;x<files.length;x=x+1){
formData.append('file[]',files[x]);
}
xhr.onload = function(){
var data = JSON.parse(this.responseText);
displayUploads(data);
}
xhr.open('post','http://localhost/project-cg/image_upload');
xhr.send(formData);
}
dropzone.ondrop = function(e){
e.preventDefault();
this.className = 'dropzone';
upload(e.dataTransfer.files);
}
dropzone.ondragover = function(){
this.className = 'dropzone dragover';
return false;
}
dropzone.ondragleave = function(){
this.className = 'dropzone';
return false;
}
}());
</script>
After I post data hidden field is still empty.
I saw your error:
You have 2 variables called uploads. One is an instance of the div and the other is the array.
What you are basically doing is assigning it a new type whenever you launch the function and in the end you have no array to pull data from. Try renaming them.
var hidden = document.getElementsByName('extra_images'); // returns a list of nodes
Try something like this :
hidden[0].value = uploads.join("|");
see mdn

Read CSV file with Javascript into a key value pair array

There are plenty of examples of reading a CSV file using jQuery however javascript examples are few and far between.
As i am using an internal script editor for a particular application, i am limited to using Javascript only.
I have a csv file that has headings followed by data in each row.
Heading1,Heading2,Heading3,Heading4
row1data1,row1data2,row1data3,row1data4
row2data1,row2data2,row2data3,row2data4
The delimiter being used is , however there could be others e.g. ^.
As i can't upload a file, i have the option to manually reference an absolute path.
Is there a way i can use only javascript to read a csv file?
As a start, here is a couple of ways to read a file with javascript
HttpRequest: (from web server or absolute path)
Source: Javascript - read local text file
function readTextFile(file)
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
And specify file:// in your filename when using an absolute path
readTextFile("file:///C:/your/path/to/file.txt");
FileReader API:
Source:
- http://codepen.io/matt-west/pen/KjEHg
- http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
HTML
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
JS
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
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!"
}
});
}
JS on MS Windows (simple sample)
Source: http://msdn.microsoft.com/en-us/library/czxefwt8(v=vs.84).aspx
function ReadFiles()
{
var fso, f1, ts, s;
var ForReading = 1;
fso = new ActiveXObject("Scripting.FileSystemObject");
ts = fso.OpenTextFile("c:\\testfile.txt", ForReading);
s = ts.ReadLine();
// s holds the text content
ts.Close();
}

Upload image using javascript

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);
}
}
});
});

Categories

Resources