Can HTML 5 drag-and-drop handle folders? - html

I'm impressed by Gmail's ability to let you drag files into emails for attachments, but when I try to drag a folder onto it, it says the file has 0 bytes. Is this a Gmail limitation, or is this something that's fundamentally not doable with the current HTML 5 spec?

Now directory upload available on chrome
you can select directory using input type
<input type='file' webkitdirectory >
and you can drag drop a folder
<div id="dropzone"></div>
var dropzone = document.getElementById('dropzone');
dropzone.ondrop = function(e) {
var length = e.dataTransfer.items.length;
for (var i = 0; i < length; i++) {
var entry = e.dataTransfer.items[i].webkitGetAsEntry();
if (entry.isFile) {
... // do whatever you want
} else if (entry.isDirectory) {
... // do whatever you want
}
}
};

The current draft of html5 only supports a file list object for handling the
getData events. so you can drag multiple files to a drag target but no folders

Related

Embed every video in a directory on webhost

This may sound silly... but is there any way to embed all videos in a directory to a webpage? I'm hosting some videos on my website but right now you have to manually browse the directory and just click a link to a video.
I know I can just embed those videos to a html page but is there any way to make it adapt automatically when I add new videos?
How you do this will depend on how you are building your server code and web page code, but the example below which is node and angular based does exactly what you are asking:
// GET: route to return list of upload videos
router.get('/video_list', function(req, res) {
//Log the request details
console.log(req.body);
// Get the path for the uploaded_video directory
var _p;
_p = path.resolve(__dirname, 'public', 'uploaded_videos');
//Find all the files in the diectory and add to a JSON list to return
var resp = [];
fs.readdir(_p, function(err, list) {
//Check if the list is undefined or empty first and if so just return
if ( typeof list == 'undefined' || !list ) {
return;
}
for (var i = list.length - 1; i >= 0; i--) {
// For each file in the directory add an id and filename to the response
resp.push(
{"index": i,
"file_name": list[i]}
);
}
// Set the response to be sent
res.json(resp);
});
});
This code is old in web years (i.e. about 3 years old) so the way node handles routes etc is likely different now but the concepts remains the same, regardless of language:
go to the video directory
get the lit of video files in it
build them into a JSON response and send them to the browser
browser extracts and displays the list
The browser code corresponding to the above server code in this case is:
$scope.videoList = [];
// Get the video list from the Colab Server
GetUploadedVideosFactory.getVideoList().then(function(data) {
// Note: should really do some type checking etc here on the returned value
console.dir(data.data);
$scope.videoList = data.data;
});
You may find some way to automatically generate a web page index from a directory, but the type of approach above will likely give you more control - you can exclude certain file names types etc quite easily, for example.
The full source is available here: https://github.com/mickod/ColabServer

exporting .txt files in html, and then importing it afterwards

So im making a website, and one of its core features I need to get working is getting the web page to export a mundane .txt file containing all the content from the forms I have.
Once that works, I also need to figure out how to import that same file back into the website and have it automatically fill in the text boxes.
How can I go about doing this?
Your question is kind of broad and doesn't show much research effort on your part. It's good form to have a go and then come here when you run into a problem, rather than just ask us to solve your problem for you. Despite that, I'll try to give you some pointers. :)
I recently had a requirement to make a button to download the contents of a div. I made a gist for future reference. You can probably adapt it to your purpose.
Basically what I did was assign a click handler to a HTML button marked 'Download'. When the button is clicked, I create a temporary anchor element on the page and set its href to the contents of the div and then programmatically click on the anchor to fire the download and finally removing the temporary anchor from the page. There's a fallback for Internet Explorer with a different method. I adapted this code from an SO answer some time ago.
var downloadButton = document.getElementById('downloadButton');
downloadButton.addEventListener('click', function () {
//get the contents of the div
var contents = document.getElementById('someDiv').innerHTML;
if (contents.length = 0) {
return;
}
var filename = 'some-filename.txt';
if (navigator.msSaveBlob) { // IE
navigator.msSaveBlob(new Blob([contents], { type: 'text/plain;charset=utf-8;' }), filename);
} else {
var link = document.createElement('a');
link.setAttribute('download', filename);
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contents));
document.body.append(link);
link.click();
document.body.removeChild(link);
}
});
As for your next requirement, upload the file and importing the data, I'll direct you to the HTML5 Rocks - file handling tutorial.
I just had a crack at a quick file uploader and I have it dumping the file contents to the console. You could, instead, parse the file contents and add the data back to your form elements as required. Here's my test code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Test Page</title>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList
for (var i = 0; i < files.length; i++) {
var reader = new FileReader();
// when the file has been read, print the contents to the console
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
console.log(evt.target.result);
}
};
var text = reader.readAsText(files[i]);
}
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('files').addEventListener('change', handleFileSelect, false);
});
</script>
</head>
<body>
<input type="file" id="files" name="files[]" multiple />
</body>
</html>

HTML input tag file handling

In this code for the PDF reader pdf-js there is an input tag to let the user upload an input file
<input id="fileInput" class="fileInput" type="file" oncontextmenu="return false;" style="visibility: hidden; position: fixed; right: 0; top: 0" />
This input tag is not a part of any form. Once the user uploads the file, where does it go? Where is the code that processes the file? (I'm asking in general, not necessarily specific to this piece of code.)
"Then it's interesting. This code doesn't have server side"
No, It doesn't.
Pdf.js is a client side program that written with javascript. So that works on javascript side.
It actually takes the file that you wanna show, and does whatever must be done like converting the buffer to Uint8Array than renders it.
All processes happen on javascript side. No server side, no file upload.
Here is an article about reading local files in javascript
Here is the related part of code in pdf.viewer.js
window.addEventListener('change', function webViewerChange(evt) {
var files = evt.target.files;
if (!files || files.length === 0)
return;
// Read the local file into a Uint8Array.
var fileReader = new FileReader();
fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
var buffer = evt.target.result;
var uint8Array = new Uint8Array(buffer);
PDFView.open(uint8Array, 0);
};
var file = files[0];
fileReader.readAsArrayBuffer(file);
PDFView.setTitleUsingUrl(file.name);
// URL does not reflect proper document location - hiding some icons.
document.getElementById('viewBookmark').setAttribute('hidden', 'true');
document.getElementById('download').setAttribute('hidden', 'true');
}, true);

Flash Builder will not read local JSON file . .

So I've tried to build a small utility to view the contents of a JSON file in an easy-to-understand manner (for non-tech people).
I have Googled far and wide, high and low, but every example that shows how to consume a JSON file in Flash Builder uses the HTTP service, pointing to a file on the web.
Here I am, sitting in front of my MacBook, wondering why I can't make this work. In the documentation I've found (sort of relating to this issue), they always show Windows examples, and they seem to work fine:
C://me/projects/json/my_json.json
Perhaps I'm completely missing the obvious, but is this possible on a Mac as well?
I've tried
file:///Users/me/projects/json/my_json.json
That doesn't work. I've tried some "resolve to path" syntax, but the HTTP service does not seem to allow for anything but file paths in quotes.
Would anyone be able to pint me in the right direction?
Use the File API. It's really easy, here's a quick code sample:
// Get a File reference, starting on the desktop.
// If you have a specific file you want to open you could do this:
// var file:File = File.desktopDirectory.resolvePath("myfile.json")
// Then skip directly to readFile()
var file:File = File.desktopDirectory;
// Add a listener for when the user selects a file
file.addEventListener(Event.SELECT, onSelect);
// Add a listener for when the user cancels selecting a file
file.addEventListener(Event.CANCEL, onCancel);
// This will restrict the file open dialog such that you
// can only open .json files
var filter:FileFilter = new FileFilter("JSON Files", "*.json");
// Open the file browse dialog
file.browseForOpen("Open a file", [filter]);
// Select event handler
private function onSelect(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
// Cast to File
var selectedFile:File = e.currentTarget as File;
readFile(selectedFile);
}
private function onCancel(e:Event):void
{
// Remove listeners on e.currentTarget
// ...
}
private function readFile(file:File):void
{
// Read file
var fs:FileStream = new FileStream();
fs.open(selectedFile, FileMode.READ);
var contents:String = fs.readUTFBytes(selectedFile.size);
fs.close()
// Parse your JSON for display or whatever you need it for
parseJSON(contents);
}
You hinted at this in your post about examples being for Windows and you being on a Mac but I'll state it explicitly here: you should always use the File API because it is cross platform. This code will work equally well on Windows and Mac.

<input type="file"> limit selectable files by extensions [duplicate]

This question already has answers here:
Limit file format when using <input type="file">?
(12 answers)
Closed 7 years ago.
How can someone limit the files that can be selected with the input type="file" element by extensions?
I already know the accept attribute, but in chrome it does limit the files by the last MIME Type defined (in this case "gif") and FF4 does not even limit anything.
<input type="file" accept="image/jpg, image/gif">
Am I doing anything wrong or is there another way?
Easy way of doing it would be:
<input type="file" accept=".gif,.jpg,.jpeg,.png,.doc,.docx">
Works with all browsers, except IE9. I haven't tested it in IE10+.
NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.
Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.
Here's a simple example that only allows files that end in ".gif" to be uploaded:
<script type="text/javascript">
function checkFile() {
var fileElement = document.getElementById("uploadFile");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension.toLowerCase() == "gif") {
return true;
}
else {
alert("You must select a GIF file for upload");
return false;
}
}
</script>
<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
<input name="uploadFile" id="uploadFile" type="file" />
<input type="submit" />
</form>
However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).
However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.
Honestly, the best way to limit files is on the server side. People can spoof file type on the client so taking in the full file name at server transfer time, parsing out the file type, and then returning a message is usually the best bet.
function uploadFile() {
var fileElement = document.getElementById("fileToUpload");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension == "odx-d"||fileExtension == "odx"||fileExtension == "pdx"||fileExtension == "cmo"||fileExtension == "xml") {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "/post_uploadReq");
xhr.send(fd);
}
else {
alert("You must select a valid odx,pdx,xml or cmo file for upload");
return false;
}
}
tried this , works very well