Right now, I have created an HTTP Server on My iPhone Application and have hosted HTML there. Then Accessing it on Browser of the system that is in the same network of iPhone. I can see the File on my Browser.
Now using WebSockets I am trying to send File from Browser to Application, but It's not working. It's fine with Text Message but Not in case of Data.
As a workaround, I tried it via Base64 String, but in that case also socket Get Closed.
For uploading using JAVAScript I have written this code, here I tried by sending Base64 string in fragments of size 200 characters.
function sendFile() {
var preview = document.querySelector('img');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
var rawData = new ArrayBuffer();
reader.onloadend = function () {
var stringContent = reader.result;
preview.src = stringContent;
var array = stringContent.match(/.{1,200}/g);
for (var i = 0; i < array.length; i++) {
ws.send(array[i]);
};
}
if (file) {
reader.readAsDataURL(file);
}else {
preview.src = "";
}
}
On iPhone side, I have used WebSocket Class from Libary CocoaHTTPServer
Socket closed at this line.
EDIT
After lots of trial and Error, I come to know that This is happening If I am opening this in Browser of Mac, Not in case of any other devices' browser like iPad, iPhone. This is very weird use-case but its true.
EDIT II
After lots of wondering, I found a Clue to this, This was working nicely for iPhone, iPad, iPod & Opera browsers, because they have old websocket support, i found this from here..
In this question the Guy have the reverse case, He is trying to close the connection on these browsers, in My case It's closing on other Browsers like chrome, Mozilla, etc. It's because something called Hybi formatted packets. This might help someone to suggest the solution for my case.
I think you should look at the official CocoaHTTPServer examples. There is one for http file uploads: https://github.com/robbiehanson/CocoaHTTPServer/tree/master/Samples/SimpleFileUploadServer
ws: protocol is allowed? For example config.xml
<access origin="ws://192.168.1.xx/*"/>
Related
This question already has answers here:
Check if file has changed using HTML5 File API
(3 answers)
Closed 2 years ago.
I have a web app, where the user can select a local file as input, using the html5 FileReader API. Is there any way I can check if the file has changed, that works in modern browsers?
Historically, this was possible in some browsers by polling the file object and comparing the File.lastModifiedDate (deprecated) or File.lastModified property, as outlined in this QA: Check if file has changed using HTML5 File API. However, the spec says that lastModifiedDate and other file data should be a snapshot of the file as it looked like when the users first selected it, so this should not work (and it seems like recent versions of most browsers indeed follow the spec now, making this hack unavailable).
I was hoping to be able to check for changes by reading the file. This kind of works, but as soon as the file is changed on disk, Chrome and Firefox throw an error saying DOMException: The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired. Is there any way around this?
This is what I tried:
let oldText
setInterval(function () {
const fileObj = document.getElementById('myFileInput').files[0]
const reader = new FileReader()
reader.onload = evt => {
const text = evt.target.result
if (text !== oldText) {
console.log("The file has changed!")
oldText = text
}
}
reader.readAsText(fileObj)
}, 1000)
...or simpler:
const fileObj = document.getElementById('myFileInput').files[0]
const reader = new FileReader()
reader.readAsText(fileObj) // works
// now lets edit the file and try again
reader.readAsText(fileObj) // fails
reader.readAsText() works as expected, until the file is changed, when it throws the error mentioned above. I guess this is a security measure of sorts, though I don't fully understand what it's trying to protect the user from. What can I do instead?
This will be possible again if/when the Native File System API is implemented in browsers. It will be partially enabled in Google Chrome 85, scheduled for release in October 2020.
Unlike the FileReader API it requires a explicit user interaction, so you'd do something like this:
myFileInput.addEventListener('change', async (e) => {
const fh = await window.chooseFileSystemEntries()
// fh is now a FileSystemFileHandle object
// Use fh.getFile() to get a File object
})
I am trying to do barcode reading in HTML5/ Javascript on mobile so I can extract the barcode and post to a Ruby on Rails web service.
I am using this code for barcode reading: code by manuels which works fine (You can try out the barcode reader code here) if camera on mobile is set to a very low resolution, not at high resolution though. This method using HTML Media Capture is not ideal as user would have to switch to low resolution manually. I know one can set resolution using GetUserMedia but it's not compatible with many browser/ versions.
I am trying to resize the captured photo using a canvas, based on the canvas code here (not written by myself). The resize works as expect. I then combine the barcode reading code mentioned above in the resize function as below but the barcode reading part doesn't work.
... var interface = new Interface('./bardecode-worker.js');
interface.on_stdout = function(x) { document.getElementById('barcode').appendChild(document.createTextNode('result:
'+x)); }; ...
interface.addData(tempCanvas.toDataURL('image/jpeg'), '/barcode.jpg').then
(
function()
{
interface.run('/barcode.jpg').then
(
function() { console.log(arguments); }
);
}
)
This is manuels' original code below, and in the above code, I am trying to feed the resized image from the canvas into the interface.js instead of a FileReader:
document.getElementById('barcode_file').onchange = function(e) {
var file = e.target.files[0];
var reader = new FileReader();
document.getElementById('barcode').appendChild(document.createTextNode('running...'));
reader.onload = function(ev) {
interface.addData(ev.target.result, '/barcode.jpg').then(function() {
interface.run('/barcode.jpg').then(function() { console.log(arguments); });
})
};
reader.readAsBinaryString(file);
};
Sorry, I am quite new to javascript. Any suggestions? Or is there a better solution?
You might be interested in looking at this program which specializes in providing easier access to hardware on mobile phones.
http://bridgeit.mobi/
It installs a native app on the phone and then lets you open the app from your webpage and then passes back the scan or photo or other item.
They use a javascript library they wrote to open the app and then pass the information back to your webpage.
The library will also open the store page of the program if it is not installed the first time it a user tries to use it.
Hi I want to save a canvas locally in IE.
var img = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
I couldn't manage to download it with following ways.
1) document.execCommand("SaveAs"..
2) window.location.href = img;
3) $.fileDownload(img); // jquery download file library-
4) canvas2image // cross domain problem.
Is there a way to save canvas locally in IE without base64 or cross domain problem? Thank you very much.
I know this is late, but I stumbled on this question in my search to do the same thing and I wanted to share a solution that's working for me.
Assuming you have a data URI already, you can create a blob and then use msSaveBlob or msSaveOrOpenBlob
Example:
dataURItoBlob = function(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var array = [];
for(var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/png'});
}
var blob = dataURItoBlob(uri);
window.navigator.msSaveOrOpenBlob(blob, "my-image.png");
I used this answer for a bulk of my solution.
After typing this, I realize this doesn't really help you with the cross domain issue, so it's a partial answer at best. With that, all I can say is consider using data URIs where possible, if cross domain is an issue.
Well, it looks like this doesn't work in IE either, but since you've not listed it, I'll provide an example. This uses the HTML5 download attribute (more here), and allows the user to click a link which then downloads a file.
I'm working on the web pages of an embeded device. To exchange data between the web page and the application of this device I use xmlhttprequest.
Now I search a way to allow the client to upload a binary (to update the firmware of that device) to the server.
One big limitation : it needs to works in IE8 (a cross browser solution would be ideal, but it's mandatory to work on IE8 first...)
In detail what I have to do :
Use the <input type='file'> to select the file on the client computer
Send the file (using xmlhttprequest?) to the server
The server will reassemble the file and to whatever it need to do with it...
I was able to get a binary from the client to the server in chrome, but in IE8, my method was not compatible.
The relevant html file :
<input id="uploadFile" type="file" />
In the javascript, I tried different way to fire an event with the input file type
// does not work in IE8 (get an Obj doesnt support this property or method)
document.querySelector('input[type="file"]').addEventListener("change"),function(e)...
// tried with jQuery, does not work in IE8(I may not using it correctly...)
$('upload').addEvent('change', function(e)....
$('upload').change(function(e)....
So my first problem is : how to do a onChange event with the input type file in IE8?
Also the method I was using in chrome (found on this page : http://www.html5rocks.com/en/tutorials/file/xhr2/ ) but that is not working on IE8 :
function upload(blobOrFile) {
var xhr = new XMLHttpRequest();
xhr.open('POST', '/server', true);
xhr.onload = function(e) { ... };
xhr.send(blobOrFile);
}
document.querySelector('input[type="file"]').addEventListener('change', function(e) {
var blob = this.files[0];
const BYTES_PER_CHUNK = 1024 * 1024; // 1MB chunk sizes.
const SIZE = blob.size;
var start = 0;
var end = BYTES_PER_CHUNK;
while(start < SIZE) {
upload(blob.slice(start, end));
start = end;
end = start + BYTES_PER_CHUNK;
}
}, false);
})();
Because the document.querySelector generate an error in IE8, I don't know if the rest of this code works in IE8 (I wish it can works!)
Any help and suggestion will be greatly appreciated!!!
I noticed a blog post from Google that mentions the ability to paste images directly from the clipboard into a Gmail message if you're using the latest version of Chrome. I tried this with my version of Chrome (12.0.742.91 beta-m) and it works great using control keys or the context menu.
From that behavior I need to assume that the latest version of webkit used in Chrome is able to deal with images in the Javascript paste event, but I have been unable to locate any references to such an enhancement. I believe ZeroClipboard binds to keypress events to trigger its flash functionality and as such wouldn't work through the context menu (also, ZeroClipboard is cross-browser and the post says this works only with Chrome).
So, how does this work and where the enhancement was made to Webkit (or Chrome) that enables the functionality?
I spent some time experimenting with this. It seems to sort of follow the new Clipboard API spec. You can define a "paste" event handler and look at event.clipboardData.items, and call getAsFile() on them to get a Blob. Once you have a Blob, you can use FileReader on it to see what's in it. This is how you can get a data url for the stuff you just pasted in Chrome:
document.onpaste = function (event) {
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items)); // might give you mime types
for (var index in items) {
var item = items[index];
if (item.kind === 'file') {
var blob = item.getAsFile();
var reader = new FileReader();
reader.onload = function (event) {
console.log(event.target.result); // data url!
};
reader.readAsDataURL(blob);
}
}
};
Once you have a data url you can display the image on the page. If you want to upload it instead, you could use readAsBinaryString, or you could put it into an XHR using FormData.
Edit: Note that the item is of type DataTransferItem. JSON.stringify might not work on the items list, but you should be able to get mime type when you loop over items.
The answer by Nick seems to need small changes to still work :)
// window.addEventListener('paste', ... or
document.onpaste = function (event) {
// use event.originalEvent.clipboard for newer chrome versions
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
console.log(JSON.stringify(items)); // will give you the mime types
// find pasted image among pasted items
var blob = null;
for (var i = 0; i < items.length; i++) {
if (items[i].type.indexOf("image") === 0) {
blob = items[i].getAsFile();
}
}
// load image if there is a pasted image
if (blob !== null) {
var reader = new FileReader();
reader.onload = function(event) {
console.log(event.target.result); // data url!
};
reader.readAsDataURL(blob);
}
}
Example running code: http://jsfiddle.net/bt7BU/225/
So the changes to nicks answer were:
var items = event.clipboardData.items;
to
var items = (event.clipboardData || event.originalEvent.clipboardData).items;
Also I had to take the second element from the pasted items (first one seems to be text/html if you copy an image from another web page into the buffer). So I changed
var blob = items[0].getAsFile();
to a loop finding the item containing the image (see above)
I didn't know how to answer directly to Nick's answer, hope it is fine here :$ :)
As far as I know -
With HTML 5 features(File Api and the related) - accessing clipboard image data is now possible with plain javascript.
This however fails to work on IE (anything less than IE 10). Don't know much about IE10 support also.
For IE the optiens that I believe are the 'fallback' options are
either using Adobe's AIR api
or
using a signed applet