Can I use a local file as a source in a live page? - html

I like to use JSFiddle when designing a new interface because I find it convenient for various tools within. I'm working on the front end of a site where I want to use a video, and unlike an image, I cant just throw it up on imgur and link to it for free instant hosting while I fiddle with the interface design.
So I want to know if I can somehow use a local file on my PC as the source for an HTML video element hosted on a live site. Obviously this is trivial to do with a web project being worked on on my Desktop, but I'm not sure it can be done on a live test.
For example this would work on a page I open from my desktop, living on my PC:
<video id="Video-Player">
<source src="../movie.mp4" type="video/mp4"/>
</video>
But I don't know whether I can do the equivalent with a page living on the web.

Here's how to allow a user to select an image from their local machine. This should get you started in the right direction.
Add a file input button in the HTML
<input type="file" id="file-btn"/>
and the corresponding handler
document.getElementById('file-btn').addEventListener('change', function(e){
readFiles(e.target.files);
})
Then the code to read the files
function readFiles(files){
files = [].slice.call(files); //turning files into a normal array
for (var file of files){
var reader = new FileReader();
reader.onload = createOnLoadHandler(file);
//there are also reader.onerror reader.onloadstart, reader.onprogress, and reader.onloadend handlers
reader.readAsDataURL(file);
}
}
Now, I've only done this with images, but this is how I read the image data.
function createOnLoadHandler(file){
console.log('reading ' + file.name + ' of type ' + file.type)
function onLoad(e){
var data = e.target.result
display(data);
}
return onLoad
}
function display(data){
var img = document.createElement('img');
img.src = data;
var context = canvas.getContext('2d')
context.clearRect(0, 0, WIDTH, HEIGHT);
context.drawImage(img, 0, 0, WIDTH, HEIGHT);
}
Here is a demo of the above code.
As a side note, if you try to read images from another domain you'll run into cross origin policy issues. I would think the same problem exists for videos as well.

Related

Empty microphone data from getUserMedia

Using the following code I get all zeroes in the audio stream from my microphone (using Chrome):
navigator.mediaDevices.getUserMedia({audio:true}).then(
function(stream) {
var audioContext = new AudioContext();
var source = audioContext.createMediaStreamSource(stream);
var node = audioContext.createScriptProcessor(8192, 1, 1);
source.connect(node);
node.connect(audioContext.destination);
node.onaudioprocess = function (e) {
console.log("Audio:", e.inputBuffer.getChannelData(0));
};
}).catch(function(error) {console.error(error);})
I created a jsfiddle here: https://jsfiddle.net/g3dck4dr/
What's wrong here?
Umm, something in your hardware config is wrong? The fiddle works fine for me (that is, it shows non-zero values). Do other web audio input tests work, like https://webaudiodemos.appspot.com/input/index.html?
Test to make sure you've selected the right input, and you don't have a hardware mute switch on.

Loading test image into canvas

I'm trying to test an AngularJS service that gets handed the ImageData from a canvas, does some pattern recognition, and returns the recognized patterns. I would like to write a unit test (not an E2E test), to build the service step by step. I fail to properly load a test-png image that I can draw onto a canvas, from which I then can extract the ImageData.
I would like to learn the proper way to solve my problem: Getting the ImageData object for a test-image in a unit test. What I am currently doing, using Karma, Jasmine 2, PhantomJS:
it('simple pattern', function (done) {
var canvas = angular.element('<canvas></canvas>')
var context = canvas[0].getContext("2d")
var src = 'test/images/3x3-bw-1star.png' // Not found by PhantomJS
var src2 = "app/images/yeoman.png" // Found.
var image = angular.element('<img src="' + src + '"/>')
image.onerror = function() { // Not called.
fail("Could not load image.")
done()
}
image.onload = function() { // Not called.
context.drawImage(image[0], 0, 0)
var imageData = context.getImageData(0, 0, image.width, image.height)
expect(starFinder.findStars(imageData)).toEqual(true)
done()
}
}
Problems with this code:
PhantomJS fails to load the test-image at src (404). The production image at src2 is correctly loaded. The path is correct, and I don't see any restriction to the "app" directory anywhere.
onload is never called. Probably, the event handler is attached to late, so when the angular.element call returns, the image is loaded already.
If I call onload manually, the context is undefined.
After #MarcoCI's (correct) suggestion, I thought I was seriously working on the wrong abstraction layer. Thus, I searched for a suitable image manipulation library, and stumbled upon Caman. I then refactored the service to accept a caman object. In the test, I create a Caman object using a canvas and the image URL. Which feels correct for what I want to do: Get an image and have it analyzed.
The 404 error for the test images can be resolved by adding the image to the list of files as served-but-not-included:
{pattern: 'test/images/*.png', watched: true, served: true, included: false}
and then setting the urlRoot.
urlRoot: 'base'
The loading and event handling is done by Caman.

Print Screen to Website [duplicate]

This question already has answers here:
Using HTML5/Canvas/JavaScript to take in-browser screenshots
(7 answers)
Closed 9 years ago.
My user need to screen shot their error message throw my website. They should directly paste from clipboard in my website instead convert the jpeg. Preferable browser is Firefox. I try to use ZeroClipBoard but it works for words not images. Appreciated if anyone could advice and share any links for references.
Simple answer: you can't. There is no web-standards way to read binary data from the clipboard, I also do not believe that Flash or Silverlight does this either (Flash can expose bitmap data from the clipboard, but only under AIR, i.e. not in a browser context).
You could write a small desktop utility program that your users download and run, which will take a screenshot and upload it for them, but without that your users will have to paste the image into Paint, save to disk, and upload with an <input type="file">.
I'm not sure of the compatibility with mozilla but you should look at the onpaste event
https://developer.mozilla.org/en-US/docs/Web/API/element.onpaste
and event.clipboarddata
http://www.w3.org/TR/clipboard-apis/
Cross compatibility is probably is probably going to be an issue.
You can look at the source for wordpress plugin Image Elevator http://wordpress.org/plugins/image-elevator/
Look at admin/assests/js/image-elevator-global.js for ideas.
After looking at the plugin I got the following code to work. It reloads the page image with whatever you paste. Works on chrome but not firefox.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
document.onpaste = function (e) {
var items = e.clipboardData.items;
for (var i = 0; i < items.length; ++i) {
// uploads image on a server
var img = items[i].getAsFile();
var oData = new FormData();
oData.append('file', img);
var req = new XMLHttpRequest();
req.open("POST", "test-pastup.php");
req.onreadystatechange = function() {
setTimeout(function() {
var img = $('img').clone();
$('img').remove();
$('body').prepend(img);
}, 100);
}
req.send(oData);
return;
}
}
</script>
</head>
<body>
<img src="aaa.png" />
<input/>
</body>
</html>
for the server side - test-pastup.php
<?php
$source = $_FILES['file']['tmp_name'];
move_uploaded_file( $source, 'aaa.png' );
?>

jQuery mobile select image for later upload

I'm building a small mobile web application using JQuery Mobile. Now I want to select an image on the phone and get information about it so I can upload it later from the app. Is this at all possible?
I might be in an offline situation and should still be able to select a image I want to upload.
If your target phone's browser supports file upload input type and FileAPI (e.g. iOS 6.0 Safari)
<input type="file" name="image" accept="image/*" capture>
then you can let your user pick an existing file, or even use camera to take a shot, and read some attributes of an image file (file name, size, type, modification date).
$("input[type=file]").change(function(){
var file = $("input[type=file]")[0].files[0];
alert(file.name + "\n" +
file.type + "\n" +
file.size + "\n" +
file.lastModifiedDate);
});
You can also make a preview of a chosen file using FileReader.
<div id="preview"></div>
displayAsImage3(file, "preview");
function displayAsImage3(file, containerid) {
if (typeof FileReader !== "undefined") {
var container = document.getElementById(containerid),
img = document.createElement("img"),
reader;
container.appendChild(img);
reader = new FileReader();
reader.onload = (function (theImg) {
return function (evt) {
theImg.src = evt.target.result;
};
}(img));
reader.readAsDataURL(file);
}
}
Here is working jsFiddle

Google Chrome - download attribute of anchor tags

I've an extension which saves some files to the downloads folder. The code below is just for testing
//This lies in the background page of my extension
function fileTest(name) {
var a = document.createElement('a');
a.href = 'data:text/plain;base64,SGVsbG8gV29ybGQh'; //Hello World!
a.download = name + '.txt';
a.onclick = function (e) {console.log('[TEST] ' + name);return true;};
a.click();
}
window.onload = function() {
fileTest('test1');
fileTest('test12');
fileTest('test123');
}
only the first file "test1.txt" is saved to the disk, although the output of the console shows that there was 3 clicks
[TEST] test1
[TEST] test12
[TEST] test123
Is this an intentional limitation by the browser ? or there's something wrong with the code ?
When I run your code in a regular browsing session, I get a slide out notification (at the top of the window) that says
This site is attempting to download multiple files. Do you want to allow this?
So, yes, it is a security limitation of the browser to restrict downloads that are not user-initiated. You probably don't see the notification because the action is being performed by your background page.
The limitation seems to be one download per user action as demonstrated in this variant of your code:
window.onclick = function() {
fileTest('test1');
}
This will allow unlimited downloads, but only one download per click event.