I am currently working on a web media player and would like to use the new "Folder Upload API" from Google Chrome (or however its being called officially) to recursively work with local directories. Unfortunately I wasn't able to find any further information on this and I'm not quite familiar with HTML5's FileReader object. Is there any official site or documentation of that specific API by any chance?
Without posting the entire and minor code of my example, I would like to refer to a JSFiddle site: http://jsfiddle.net/a869q/
The example displays both, the 'usual' upload method and the one using webkit-directory.
<input id="file_input" type="file" multiple="" />
<input id="file_input_dir" type="file" multiple="" webkitdirectory="" directory="" />
<div id="test"></div>
On event.change the references (blobs) to these files are then being used to get duration of mp3-files and to create a list of audio-elements. Works just fine. Choosing directories only works in Chrome.
$('#file_input, #file_input_dir').change(function(e) {
$.each(e.target.files, function(index,file) {
// ....
$('#test').append('<audio src="'+window.URL.createObjectURL(file)+'"></audio>');
// ....
});
});
Now, using Javascript / jQuery I would like to find out if the client does support the new webkit-directory feature and I really hope that there is a way doing this without just reading the UserAgent and check against string "Chrome". Any ideas?
Regarding the matter, that it's only working in Chrome at the moment, I would also like to know if there is a common or suitable workaround to let this work in different browsers, but at least Firefox. In this article there have been some neat posts made with different examples already. But mainly all the working plugins are using Flash or Applets which I'm really trying to avoid. Still hoping for solution.
In addition, talking about the method I'm gathering the duration of chosen audio-files with (please see JSFiddle). Any way doing this with pure JScript, without creating HTML5-Audio-Elements?
(function() {
var input = document.createElement("input");
input.type = "file";
return !!("webkitdirectory" in (input || document.querySelectorAll("input[type=file]")[0] ))
}())
Related
I'm trying to use AWS cloudSearch on my site, and I'm missing something fundamental. I've had no luck finding a working example.
In my HTML head I've included the SDK. per: http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-intro.html
<script type="text/javascript" src="https://sdk.amazonaws.com/js/aws-sdk-2.0.31.min.js"></script>
Then in my script tag I have this snippet (with my creds, not the ones shown here). I used hard coded creds for my testing per: http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-configuring.html
var s3 = new AWS.S3({region: 'ap-southeast-2', maxRetries: 15});
AWS.config.update({accessKeyId: 'akid', secretAccessKey: 'secret'});
console.log(AWS);
//
var cloudsearch = new AWS.CloudSearch();
When it tries to execute the last line javaScript tells me: Uncaught TypeError: undefined is not a function
I've been unable to find a demo, example or tutorial. The docs don't even have working examples.
Can you help?
Thank you for your time.
That error is saying it doesn't find reference to cloudsearch when you are calling the new AWS.Cloudsearch().
The script you reference doesn't appear to have a reference to cloudsearch api. I think you need to build it out like they specify in Building the SDK for Use in the Browser.
For kicks I replicated the error you received, then did a browser build as specified by the link above. It worked.
Upon further investigation after looking through the libraries. I think you probably want to use CloudSearchDomain to issue searches to a given domain setup within cloudsearch.
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudSearchDomain.html
The other cloudsearch library is all administrative/setup related to Search domain creation and other administrative types of objects. Looks like there are some issues with CORS/setup for cloudsearch in general so if you want to issue this straight from the browser might be a bit tricky.
The most common way to get around the CORS issue is to use a proxy.
The easiest way to play around with search from the browser\local is using a form, as suggested here.
Amazon CloudSearch query
<form action="https://$YOURSEARCHDOMAIN/2013-01-01/search" method="get">
<label>Search: <input name="q" /></label>
<input type="hidden" name="q.parser" value="simple" />
<button type="submit">Search</button>
</form>
above solution is pretty much cut and paste\play, works like the AWS cloudsearch console, and returns the json to the browser. Not sure if you can incorporate suggests without the api directly. You will need to open up your access policy to work, I believe.
I tried a variety of access policies and various tricks to get around the CORS issue, all no dice.
You actually need the CORS plugin for chrome to make this work properly.
Created an angularjs project that demos this and added to git hub. You need CORS-anywhere to route properly to the domain.
https://github.com/tkntobfrk/amazon-cloudsearch-angular
project uses suggesters to search domain data and populate the input field with autocomplete data. Uses bootstrap.ui typeahead.
While developing a pattern generator I am running into the same problem described in this question from 2011.
The answers given don't really offer a cross-browser, client-side solution.
I would accept any of the following solutions when clicking the Export Pattern button:
Triggering a download through canvas2image while ensuring that the file is saved with a .png extension (no matter what the filename is set to) or,
Display a widget (KendoUI preferably) with the image resulting from the Canvas2Image.saveAsPNG() method and let the user save it from there preferably not using the lame right-click solution, but with a link or a button.
HTML for the button I'm currently using:
<button id="downloadbtn" onClick="javascript:downloadImage()" data-role="button" class="k-button">Export Pattern</button>
Function that triggers the download:
function downloadImage () {
//...extra code omitted
var oCanvas = document.getElementById("my_canvas");
oCanvas.width = $("#pixels-h").val();
oCanvas.height = $("#pixels-v").val();
Canvas2Image.saveAsPNG(oCanvas);
//...extra code omitted
}
The file seems to download fine under OSX with Chrome Version 23.0.1271.95 and Safari Version 5.1.7 (6534.57.2).
I have a report of someone unable to open the file after downloading it under Firefox 17.0.1 for OSX. Apparently the download generates a .part file.
The biggest issue is that without a file extension I doubt that this method can be reliable.
I am looking for a client-side only solution with the widest possible compatibility with current browsers, so I guess the HTML5 download attribute would not do the trick as it is currently only supported in Chrome.
Any creative solutions?
I ran into the same issue. The basic problem is the filename needs to be added in the header but canvas2images uses document.location.href = strData and strData doesnt have headers. So the answer is, canvas2image does not support the feature we need, and we will need to try another solution. (for example perhaps FileSaver.js and canvas-toBlob.js)
http://eligrey.com/demos/FileSaver.js/
I want to read a directory and fill a list with the name of those files.
Is it possible to do this tasks using javascript?
No, for security reasons.
You might be able to do it by invoking ActiveX or Flash and having the user agree to permit file system access from these plugins, but - please don't.
Edit 10 years on:
Not only please don't do this, but now outside of using an old device without updates - you can't do this with Flash/ActiveX.
It's 2022, a lot of changes in the world and beyond, and, lo and behold, now we have something called File System Access API:
This API allows interaction with files on a user's local device, or on
a user-accessible network file system. Core functionality of this API
includes reading files, writing or saving files, and access to
directory structure.
It became available in Chrome 86 (released in October 2020). Safari added support in 15.2 version, released in the end of 2021. To the moment of writing this, Firefox doesn't support this feature though (here's the related discussion).
Also, security considerations didn't go anywhere:
This API opens up potential functionality the web has been lacking.
Still, security has been of utmost concern when designing the API, and
access to file/directory data is disallowed unless the user
specifically permits it.
This part is no longer relevant (kudos to #gignu for mentioning that in the comments) and is left here for historical reasons.
I suppose the closest you might get by using webkitdirectory attribute:
HTML
<input type="file" id="file_input" webkitdirectory="" directory="" />
<div id="list_of_files"></div>
...
JS
var $list = $('#list_of_files');
$('#file_input').change(function(event) {
var listOfFiles = event.target.files;
for (var i = 0, l = listOfFiles.length; i < l; ++i) {
$list.append($('<p>'+ listOfFiles[i].name +'</p>'));
}
});
... as shown here. But it works in Chrome only (and suggested usage of mozdirectory attribute didn't help).
You can try to use FileReader object, but it poorly supported by browsers.
In google chrome you may prompt the client to select a directory and then use this to list the files contained in the directory and its subdirectories:
<input type="file" webkitdirectory onchange="listContents(this.files)">
listContents would be your implementation.
I don't know if you're doing security research etc etc.. So besides from saying "you shouldn't do it", the actual answer to the question is, you can actually READ files by taking advantage poorly-written JS code, that's why you should code.. defensively.
Then there's this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Yes depending on the browser you have.
Even though it is not a common practice but you can using certain browsers such as Chrome (using the requestFileSystem supported by webkitRequestFileSystem) or in Internet Explorer using File System Object.
if (window.ActiveXObject) {
try {
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile("C:\\Program Files\\GM4IE\\scripts\\source.txt","C:\\Program Files\\GM4IE\\scripts\\target.txt", 1);
fso = null;
}
catch (e) {
alert (e.message);
}
}
I am getting error :
"Automation server can not create object" on the line where I am creating ActiveXObject instance.
I understand that it's considered very bad to access hard-drive data using javascript but I just need it.
I am using IE8 , Greasemonkey4IE to run my javascript.
Thank you,
Mohit
******************************
function WriteFile()
{
var fso = new ActiveXObject("Scripting.FileSystemObject");
fso.CopyFile("C:\\source.txt","C:\\target.txt", 1);
}
I've put the above code inside a simple HTML page and it worked perfect.
http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm
You can find the similar code on above mentioned location.
I modified it a bit, tough.
But when I am trying to run it through GreaseMonkey4IE it simply spitting the same error I specified earlier.
I did it guys, but thanks a lot for your quick and helpful replies.
All I did is :
Go to Tools > Internet options > Security > Custom Level
Under the ActiveX controls and plug-ins, select Enable for Initializing and Script ActiveX controls not marked as safe.
Using native JavaScript, no, it is not generally possible to access a local file. Using plugins and extensions like ActiveX, Flash, or Java you can get around this rule, generally with some difficulty.
For some browser and OS specific exceptions to this general rule, you might want to have a look here:
Local file access with javascript
Note that as of late 2012, the FileReader API has been supported in all major browsers and provides a native JavaScript mechanism for accessing local files that the user nominates (via an input element or by dropping them into the browser).
This still cannot be used to access an arbitrary file by name/path as in the examples in the original question.
HTML5 File API has multiple ways to access local files.
window.requestFileSystem allows you to request access to the filesystem. Browser support is very poor on this (Chrome only).
FileReader is the HTML5 FileReader API that allows you to programatically read files that users select through a <input type='file' /> Browser support is better on this.
You should use fallbacks like flash and POST to a server for full file access.
Generally reading arbitary files is considered "cheating the browser" so I you'll either have to use secure HTML5, ActiveX or Flash. All 3 of those require user permissions.
After some research I have found:
var fso = new ActiveXObject("Scripting.FileSystemObject");
//This line will create a xml file on local disk, C drive
fh = fso.CreateTextFile( "C:\\fileName.xml", true);
fh.WriteLine("this is going to be written in fileName.xml");
This is how we can do it.There are other methods also.
Accessing local file system is very bad thing to do but yes we can do it.
Automation server can not create object
To get rid of this error go to Tools → Internet Options → Security → select Internet icon → click Custom level → select Enable for Initialize and script ActiveX controls not marked as safe for scripting.
I have not tested this on any other berowser except IE8, but I am sure it will work.
I am writing a small application with Qt 4.6 (64-bit Arch Linux, though that shouldn't matter) which lets the user edit a document using a QWebView with contentEditable turned on. However, for some reason embedding an image does not work. Here is a code snippet:
void LeafEditView::onInsertImage()
{
// bring up a dialog, ask for an image
QString imagePath = QFileDialog::getOpenFileName(this,tr("Open Image File"),"/",tr("Images (*.png *.xpm *.jpg)"));
ui->leafEditor->page()->mainFrame()->documentElement().evaluateJavaScript("document.execCommand('insertImage',null,'"+imagePath+"');");
}
The test image does in fact exist and yet absolutely nothing happens. Bold / italics / underline all work fine via JavaScript, just not images. Thoughts?
Check that QWebSettings::AutoLoadImages is enabled.
You could also try:
document.execCommand('insertImage',false,'"+imagePath+"');
Try using relative vs absolute paths to the image.
Last but not least, poke around this sample application -- they are using a similar method of Javascript execCommand(), they do some things in a slightly different way such as using QUrl::fromLocalFile.
Best of luck!
It turns out that WebKit has a policy of not loading resources from the local filesystem without some massaging. In my code, I have a WebKit view which I'm using to edit leaves in a notebook. The following one-liner solved my issue:
ui->leafEditor->page()->mainFrame()->setHtml("<html><head></head><body></body></html>",QUrl("file:///"));
From what I gleaned by lurking around the WebKit mailing list archives, in order to load files from the local filesystem one must set the URI to be file:, and this does the job.