strange filename callback after file selection finish - javascript

I have this code which will display the file name after file has been selected:
<input id="file-input" type="file" />
<script>
const fileInput = document.querySelector('#file-input');
fileInput.onchange = function(){
console.log('file name:', this.value)
}
</script>
I prepared two windows shortcut file (produced by Desktop ---> right click ---> new ---> shortcut)
the first shortcut file
the target is https://www.baidu.com/ and the file name is www.baidu.com
after i select this file, the output is C:\fakepath\www.baidu.com.url in callback, which is working as expected
the second shortcut file
target is https://www.google.com/ and the file name is www.google.com
but after select this file, i expect it to output C:\fakepath\www.google.com.url in callback, but it outputs something like C:\fakepath\TQCJEVEM
Why is this happening?

Disclaimer: I'm still not sure about the why, but I can make a guess about what is happening.
When you create a windows shortcut (like you mentioned above) where the target is a Network Resource, it creates a URL file that has a .url extension.
NOTE: Microsoft Windows does not display the ".url" file extension even though it exists in the filename. Therefore, URL files saved using Windows web browsers will appear with only the filename prefix.
A URL file on windows looks something like this:
[{000214A0-0000-0000-C000-000000000046}]
Prop3=19,11
[InternetShortcut]
IDList=
URL=https://www.baidu.com/
HotKey=0
When you upload the baidu shortcut, windows simply uploads the file with above content.
HOWEVER
When you upload the google shortcut, windows actually downloads a copy of the www.google.com website landing page, stores it in the local cache somewhere in the ..\AppData\Local\Microsoft\Windows\INetCache\.. folder and then uploads that cache file which could have its filename as a randomly generated string. Every new attempt would generate a new string for filename.
Hope this points you in the right direction.
Edit:
To verify the content of the uploaded file, slightly modify your code using sample code from this answer.
function init() {
document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}
function handleFileSelect(event) {
const reader = new FileReader()
reader.onload = handleFileLoad;
reader.readAsText(event.target.files[0])
}
function handleFileLoad(event) {
console.log(event);
document.getElementById('fileContent').textContent = event.target.result;
}
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
</head>
<body onload="init()">
<input id="fileInput" type="file" name="file" />
<pre id="fileContent"></pre>
</body>
</html>

Related

Firebase could storage corrupts special characters in uploaded file

I have uploaded a js file to firebase cloud storage and made it public.
Also after uploading via google cloud console edited the metadata and set the content-language to unset , content-type to text/javascript and content-encoding to UTF-8. But still, the special characters such as äöå are shown corrupted
The usage of the JS file is like below ;
On a website, I have a script tag on <head/>
<head>
<script src="https://storage.googleapis.com/myapp.appspot.com/MyElement.js"
charset="UTF-8" or "iso-8859-1" <-- have tried both
type="text/javascript" />
</head>
...
<body>
...
<div id="locationForMyCustomEl"></div>
...
</body>
the content of the javascript file is something like
function setup(){
let element = document.querySelector("#locationForMyCustomEl");
element.innerHTML = "<h1> Köp för item </h1>"
/*
Have Also tried:
K\u00F6p f\u00F6r item
Köp för item
*/
}
setup();
But I always receive messed up characters like Köp för item in the resulting <h1/> tag.
If I open the javascript file in a browser (inserting the URL https://storage....lement.js)
the represented code also contains messed-up characters.
like
function setup(){
let element = document.querySelector("#locationForMyCustomEl");
element.innerHTML = "<h1> Köp för item </h1>"
}
It seems the uploaded file gets corrupted, and there is no way to restore it via charset.
How should I use special characters in an external javascript file?

jQuery/ Javascript .get method for reading text files

I just started working on my school assignment with some regular expressions in Javascript. I can't seem to figure out how to actually read data from a text file into variable using jQuery method .get(). When I try my code out nothing happens. It seems like it never enters .get() section. Here is my code:
JS file:
document.getElementById('file').onchange = function(){
var file = "New Text Document.txt"; //this will later be the selected file
$.get(file,function(data){
var myVar = data;
$("#123").html(myVar);
});
};
HTML file:
<!DOCTYPE html>
<html>
<head>
<title>animacija</title>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<input type="file" name="file" id="file">
<script type="text/javascript" src="func.js"></script>
<div id="123"></div>
</body>
</html>
The code snippet seems to be ok, but it will not work locally since $.get is for ajax requests and requires full available server path.
I rather recommend you the use of FileReader API.
HTML
<title>animacija</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body>
<input type="file" name="file" id="file">
<div id="123"></div>
</body>
JavaScript
document.getElementById('file').onchange = function() {
var file = this.files[0];
var FR = new FileReader();
FR.readAsText(file);
FR.onload = function(data) {
var myVar = data.target.result;
$("#123").html(myVar);
}
};
JSFiddle
Hope it works for you!
Most browsers will not allow file: resources to read other local files. This is to prevent attacks where a downloaded HTML document could start reading (and transmitting) the contents of your hard drive (or at least your Downloads folder) as soon as you open it.
The other thing you need to know here is that $.get is used for getting resources from an HTTP server, while file inputs are used to allow a user to select a file from their local drive. I realize in your case it's a little confusing, because your web page is on your local hard drive, but imagine if your HTML and scripts were being hosted online, and some other user (not you) was using them to process their own locally-stored files.
MDN has a good tutorial on how to get started with <input type="file"> inputs.
The code won't work locally due to cross-origin limitations.
It works fine when run on a remote server and all files are in the same folder.
If you want to read local files (aka. files selected by user through the file input) you can read more about FileAPI here:
https://www.html5rocks.com/en/tutorials/file/dndfiles/

Chrome extension form input text is blank on submit

I'm trying to build a chrome extension that downloads a bunch of items from links, the main logic is in my download.js file and I want to be able to specify in which downloads subfolder I'd like to bundle them all but the value of the input field seems to be empty. Here's my code so far
popup.html
<!doctype html>
<html>
<head>
<title>Download CVs</title>
<script src="popup.js"></script>
</head>
<body>
<form id="folderForm">
Subdir of downloads:
<input type="text" id="folder">
<input type="submit" id="download" value="Download CVs">
</form>
</body>
</html>
popup.js
function bundleItems() {
chrome.tabs.executeScript({
file: 'download.js'
});
}
document.addEventListener('DOMContentLoaded', function() {
var downloadButton = document.getElementById('download');
downloadButton.addEventListener('click', bundleItems);
});
chrome.extension.onRequest.addListener(function(logs) {
var folder = document.getElementById('folder').value;
logs.map(function(log) {
chrome.downloads.download({
url: log.attachment.link,
filename: folder + '/' + log.attachment.filename
});
});
});
I'm sending information from download.js to popup.js and everything works if I try to download it in downloads, so I feel posting my download.js file will be useless. However, if I try to display the folder variable, it's empty. I've searched for lots of other posts on the same issue and none of the solutions seem to work for me.
You cannot submit to a Chrome extension page. There is no web server to process your POST request in this case. Doing so simply reloads the document (clearing your value from the form).
You need to prevent submitting instead, by specifying type="button" for your button.
I would add preventDefault() on submit button.
https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault

passing csv file to Ruby using JS and html's input File API

I'm trying to build basic CSV editor which uses html+css as a UI, and Ruby doing the string parsing and manipulation.
function passFileToRuby (f) {
var reader = new FileReader(),
txt
reader.readAsText(f);
txt = reader.result
return txt
}
and some html:
<html>
<head>
<script src="../js/script.js"></script>
</head>
<body>
<h1>CSVEditor!</h1>
<form action="/form" method="post">
<input type="file" name="file" id="input" onchange="passFileToRuby(this.files[0])">
<input type="submit">
</form>
</body>
</html>
I am trying to load a csv file via html form, pass it to Ruby (Sinatra) which will split it and render it as table content.
When I load a file and then enter the contents of passFileToRuby() line after line everything seems to work - console.log(txt) prints the contents of the file to the screen. When I pass it to onchange attribute as a passFileToRuby function however, it returns nothing, txt is null.
Please advise.
The file might not be loaded yet when the input changes - it's too soon. When you access from the console, the browser has had the time to upload the contents.
Try attaching a loaded event handler to reader instead of accessing its result directly.
var reader = new FileReader();
reader.onload = function(evt) {
handleText(reader.result);
}
reader.readAsText(f);
and implement handleText appropriately.

Javascript to check filesize before upload in Internet Explorer

Is it possible to use Javascript to check for a file's size (at the client side) before it is actually uploaded to the server?
The application is built on EXTJS and Java and is restricted to usage by Internet Explorere 7 on Windows XP machines. No usage of activeX is allowed.
The workflow is as such:
User selects a file to upload.
Validation kicks in immediately to check for file type and filesize.
If filesize exceeds limit, the GUI will prompt with error.
If filesize is within the limit, the full filepath will be passed to the server end (java servlet) to be uploaded.
Is the filesize check and reading of full file path possible to be achieved with javascript?
It is possible with ActiveX Objects.
<html>
<head>
<script>
function getSize()
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>
There's currently no way to portably check the size of an uploaded file from the web browser. The HTML5 File API makes this possible, but that's not available in MSIE7 -- it's currently on track for MSIE10.
There is intentionally no way to determine the full path of an uploaded file, as that may include sensitive information, like the name of the end user.
The reason you can't is because it would be bad if browsers, and javascript, could access the clients filesystem.
This is actively denied and can be seen as an attack.
Using jQuery, Restricting File Size Before Uploading
Please try below code,
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(function() {
$("document").ready(function(){
$("#myFile1").change(function() {
var f1=document.getElementById("myFile1").value;
if((f.size||f.fileSize)==09765625)
{
alert("file size is less than 1mb");
}
else
{
alert("file size should not exceed more than 1mb");
$(this).val($.data(this, 'f'));
return false;
}
});
});
})
</script>
</head>
<body>
<input type='file' name="file" id="myFile1" />
</body>
</html>

Categories

Resources