When reading a file from the input element by the FileReader api it works, but my android device also allows sending files and it seems to send heic files anyway which then results in an empty image without any errors in the console. Also the orientation is wrong when getting an image directly from the camera. I just found heavy librarys to implement and i am looking for a smarter solution.
JavaScript
function previewFile( e ) {
var preview = document.getElementById('usersProfilePicture');
var file = e.files[0];
var reader = new FileReader();
reader.onloadend = function () {
preview.src = reader.result;
}
if (file) {
reader.readAsDataURL(file);
} else {
preview.src = "";
}
}
HTML5
<form>
<label>
<input id="uploadProfilePicture" name=file type=file accept="image/jpg, image/jpeg, image/png, image/gif, image/bmp">
</label>
</form>
There are no error messages at all. Firefox, Chrome both on desktop and android allow .heic files no matter what accept attribute i set.
worst solution: deny acceptance of .heic files
best solution: make fileReader work with .heic files.
in between solution: detect heic and convert it to jpeg, clientside.
The answer above explains this very well but for anyone looking for another example I have slightly modified the example from Heic2Any (https://alexcorvi.github.io/heic2any/)
<input type="file" id="heic" onchange="convertHEIC(event)">
async function convertHEIC (event){
let output = document.getElementById('output');
//if HEIC file
if(event.target.files[0] && event.target.files[0].name.includes(".HEIC")){
// get image as blob url
let blobURL = URL.createObjectURL(event.target.files[0]);
// convert "fetch" the new blob url
let blobRes = await fetch(blobURL)
// convert response to blob
let blob = await blobRes.blob()
// convert to PNG - response is blob
let conversionResult = await heic2any({ blob })
// convert to blob url
var url = URL.createObjectURL(conversionResult);
document.getElementById("target").innerHTML = `<a target="_blank" href="${url}"><img src="${url}"></a>`;
}
};
I have a workaround for this issue for now by using the library heic2any
(https://github.com/alexcorvi/heic2any)
check to see if file from input is .heic, then use library like so:
heic2any({
// required: the HEIF blob file
blob: file,
// (optional) MIME type of the target file
// it can be "image/jpeg", "image/png" or "image/gif"
// defaults to "image/png"
toType: "image/jpeg",
// conversion quality
// a number ranging from 0 to 1
quality: 0.5
})
I wrap this call in a promise and then pass the result to the file reader:
// uploadHEIC is a wrapper for heic2any
uploadHEIC(heicFile).then(function (heicToJpgResult) {
var reader = new Filereader();
reader.onload = function () {
// Do what you want to file
}
reader.readAsArrayBuffer(heicToJpgResult);
}
A few things to note to get this working properly.
First, in windows the assigned mime type for heic and heif is blank. Not sure when this bug will get fixed, but for now you can't rely on mime type in your scripts or input tag. I needed to add the heic and heif file extensions in the accept parameter of my input tag:
<input type="file" accept="image/*,.heic,.heif" />
and in my script I created a function to check the file extension for heic and heif if mime type was blank.
function isHEIC(file) { // check file extension since windows returns blank mime for heic
let x = file.type ? file.type.split('image/').pop() : file.name.split('.').pop().toLowerCase();
return x == 'heic' || x == 'heif';
}
Also, heic2any is pretty large (even if minified and compressed). I decided to load it dynamically only when needed.
function loadScript(url, callback) {
var script = document.querySelectorAll('script');
for (var i = 0; i < script.length; i++) {
if (script[i].src === url) {
script = script[i];
if (!script.readyState && !script.onload) {
callback();
} else { // script not loaded so wait up to 10 seconds
var secs = 0, thisInterval = setInterval(function() {
secs++;
if (!script.readyState && !script.onload) {
clearInterval(thisInterval);
callback();
} else if (secs == 10) {
clearInterval(thisInterval);
console.log('could not load ' + url);
}
}, 1000);
}
return;
}
}
script = document.createElement('script');
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
if (script.readyState) {
script.onreadystatechange = function() {
if (script.readyState === 'loaded' || script.readyState === 'complete') {
script.onreadystatechange = null;
callback();
}
}
} else {
script.onload = function() {
script.onload = null;
callback();
}
}
script.src = url;
}
I my use case I'm leveraging heic2any to prepare images for upload. If the image is heic I convert it to png (blob), then pass the result to another utility (image blob reduce) to resize and sharpen before converting to jpg in preparation for upload. However, for the sake of simplicity the example below uses heic2any to convert to jpg in 1 step before upload.
function convertHEIC(file) {
return new Promise(function(resolve) {
if (!isHEIC(file)) return resolve(file);
loadScript('https://cdn.jsdelivr.net/npm/heic2any#0.0.3/dist/heic2any.min.js', function() {
heic2any({
blob: file,
toType: "image/jpg"
}).then(function (convertedFile) {
convertedFile.name = file.name.substring(0, file.name.lastIndexOf('.')) + '.jpeg';
resolve(convertedFile);
});
});
});
}
// convert any heic (and do any other prep) before uploading the file
convertHEIC(file).then(function(file) {
// code to upload (or do something else with file)
.
.
.
}
Related
I have an Ionic application which downloads a file from a Web API. The content of the file can be found in the _body property of the HTTP response.
What I'm trying to do is convert this text into an arrayBuffer so I can save the content into a file.
However, the issue that I'm having is that any file (PDF files in my instance) that have images and/or large in size either don't show up at all or show up as correputed files.
At first I thought this was an issue relating Ionic. So to make sure I tried to simulate this issue and I was able to reproduce it.
Is this snippet you can select a PDF file, then download it. You would find that the downloaded file is corrupted and exactly how my Ionic app displays them.
HTML:
<input type="file" id="file_input" class="foo" />
<div id="output_field" class="foo"></div>
JS:
$(document).ready(function(){
$('#file_input').on('change', function(e){
readFile(this.files[0], function(e) {
//manipulate with result...
$('#output_field').text(e.target.result);
try {
var file = new Blob([e.target.result], { type: 'application/pdf;base64' });
var fileURL = window.URL.createObjectURL(file);
var seconds = new Date().getTime() / 1000;
var fileName = "cert" + parseInt(seconds) + ".pdf";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = fileURL;
a.download = fileName;
a.click();
}
catch (err){
$('#output_field').text(err);
}
});
});
});
function readFile(file, callback){
var reader = new FileReader();
reader.onload = callback
//reader.readAsArrayBuffer(file);
reader.readAsText(file);
}
https://jsfiddle.net/68qeau3h/3/
Now, when using reader.readAsArrayBuffer(file); everything works as expected, however in my particular case, I used reader.readAsText(file); because this is how the data is retrieve for me, this is text form.
When adding these lines of code to try to convert the string into an arrayBuffer
...
var buf = new ArrayBuffer(e.target.result.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=e.target.result.length; i<strLen; i++) {
bufView[i] = e.target.result.charCodeAt(i);
}
var file = new Blob([buf], { type: 'application/pdf' });
...
This will not work and generate PDF files that the browser can't open.
So to recap, what I'm trying to do is somehow convert the result I get from reader.readAsText(file); to what reader.readAsArrayBuffer(file); produces. Because the files I'm working with, or the data im retrieving from my backend is this text form.
I understand that providing a physical file path to javascript is not possible due to security reasons. However, when I look at Mozilla's pdf.js and mupdf android pdf viewer I see this is very much possible. There is a mechanism by which I can pass a file path to javascript. I explored into PDF.js but it seemed little difficult to make use of when I needed a simple solution.
I want to pass android internal storage file location onto the following code instead of using input id="files" type="file" which requires me to browse and select file. In my case I want to just pass file location from sdcard.
The following code actually loads ms word (docx) file as html which I then will show in webview in my project. In the case of pdf.js we were using it to display pdf in the similar way.
<script>
$(document).ready(function(){
//Input File
var $files = $('#files');
//File Change Event
$files.on('change', function (e) {
//File Object Information
var files = e.target.files;
//Create DocxJS
var docxJS = new DocxJS();
//File Parsing
docxJS.parse(
files[0],
function () {
//After Rendering
docxJS.render($('#loaded-layout')[0], function (result) {
if (result.isError) {
console.log(result.msg);
} else {
console.log("Success Render");
}
});
}, function (e) {
console.log("Error!", e);
}
);
});
});
</script>
<input id="files" type="file" name="files[]" multiple="false" />
<div id="loaded-layout" style="width:100%;height:800px;">
</div>
You can check code of PDF.JS based pdfviewer in android here.
What I found on the PDF.js code which was used to input file :
In pdffile.js included in index.html file, url variable was mentioned pointing to real location of the file i.e. in assets folder which then was used in pdf.js but at that point the usage seems confusing. Is there any way by which I can use real path of file or pass real path somehow in android for my purpose of viewing docx?
UPDATE :
I find that PDF.js by Mozilla actually treats file location as a url and so the file in the url is converted to javascript file object or blob. Hence I create a blob of the url from server using Ajax :
var myObject;
var xhr = new XMLHttpRequest();
xhr.open("GET","10143.docx",true); // adding true will make it work asynchronously
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200){
//do some stuff
myObject = this.response;
}
};
xhr.send();
$(document).ready(function(){
//Input File
var $files = $('#files');
//File Change Event
$files.on('change', function (e) {
//File Object Information
var files = myObject.files;
//Create DocxJS
var docxJS = new DocxJS();
//File Parsing
docxJS.parse(
blobToFile(myObject, "10143.docx"),
function () {
//After Rendering
docxJS.render($('#loaded-layout')[0], function (result) {
if (result.isError) {
console.log(result.msg);
} else {
console.log("Success Render");
}
});
}, function (e) {
console.log("Error!", e);
}
);
});
});
function blobToFile(theBlob, fileName){
//A Blob() is almost a File() - it's just missing the two properties below which we will add
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
However now that I do that I get Parsing error from DocxJS like : {isError: true, msg: "Parse Error."}
I am building a video surveillance application where the requirement is to save recorded video feeds to the server so that they can be served up to the viewer later. Am using MediaRecorder API to do so, and as the continuous stream would end up in a very large file difficult to be posted all at once, i plan to chop the stream blob into multiple chunks and keep posting periodically. Now the recording event is fired with a toggle switch in html page and then Javascript takes over.
Here is the code that i have so far:
HTML:
some code...
<div class="onoffswitch">
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="switch1">
<label class="onoffswitch-label" for="switch1" onclick="toggleVideoFeed();">
<span class="onoffswitch-inner"></span>
<span class="onoffswitch-switch"></span>
</label>
</div>
some code...
JavaScript:
var mediaRecorder;
var pushInterval = 6000;
var id, counter = 0;
// var formData;
function toggleVideoFeed() {
var element = document.getElementById("switch1");
element.onchange = (function (onchange) {
return function (evt) {
// reference to event to pass argument properly
evt = evt || event;
// if an existing event already existed then execute it.
if (onchange) {
onchange(evt);
}
if (evt.target.checked) {
startRecord();
} else {
stopRecord();
};
}
})(element.onchange);
}
var dataAvailable = function (e) {
var formData = new FormData();
var fileName = "blob" + counter + ".mp4";
console.log("data size: ", e.data.size);
var encodeData = new Blob([e.data], { type: 'multipart/form-data' });
formData.append("blob", encodeData, fileName);
var request = new XMLHttpRequest();
request.open("POST", "/Device/Upload", false);
request.send(formData);
counter++;
}
function startRecord() {
navigator.getUserMedia = (navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia);
if (navigator.getUserMedia) {
navigator.getUserMedia(
// constraints
{
video: true,
audio: false
},
// successCallback
function (stream) {
mediaRecorder = new MediaRecorder(stream);
mediaRecorder.start();
mediaRecorder.ondataavailable = dataAvailable;
// setInterval(function () { mediaRecorder.requestData() }, 10000);
},
// errorCallback
function (err) {
console.log("The following error occured: " + err);
}
);
} else {
console.log("getUserMedia not supported");
}
}
function stopRecord() {
mediaRecorder.stop();
}
Controller-C#
[HttpPost]
public JsonResult Upload(HttpPostedFileBase blob)
{
string fileName = blob.FileName;
int i = Request.Files.Count;
blob.SaveAs(#"C:\Users\priya_000\Desktop\Videos\" + fileName);
return Json("success: " + i + fileName);
}
THE PROBLEM:
When i try playing the received .mp4 files as i get them on the server end, i can play just the first file blob0 and the rest although they show similar sizes to the first file (4 mb each) do not contain any video data. Is it possible that the data i receive on the other end is corrupt/ garbled? Or is there something wrong with my code. Please help guys - Have been trying to solve this problem since the last 10 days with no clue how to figure it out.
mp4 files have a header which is put at the beginning of the file. The header contains information used to initialize the decoder and without it the file cannot be played. Try concatenating the files (the first one and the second one) and see if the whole file plays. If yes then the problem is a missing header. If not please send me the two files so I can inspect them and see what exactly is stored in these.
There is no way AFAIK to instruct MediaRecorder to append the header to each blob of video. You have to do it manually.
PS. sorry for the late response.
You can use RecordRTC by Muaz Khan and use the MVC Section to record and save video to the server.
I'm trying to upload generated client side documents (images for the moment) with Dropzone.js.
// .../init.js
var myDropzone = new Dropzone("form.dropzone", {
autoProcessQueue: true
});
Once the client have finished his job, he just have to click a save button which call the save function :
// .../save.js
function save(myDocument) {
var file = {
name: 'Test',
src: myDocument,
};
console.log(myDocument);
myDropzone.addFile(file);
}
The console.log() correctly return me the content of my document
data:image/png;base64,iVBORw0KGgoAAAANS...
At this point, we can see the progress bar uploading the document in the drop zone but the upload failed.
Here is my (standart dropzone) HTML form :
<form action="/upload" enctype="multipart/form-data" method="post" class="dropzone">
<div class="dz-default dz-message"><span>Drop files here to upload</span></div>
<div class="fallback">
<input name="file" type="file" />
</div>
</form>
I got a Symfony2 controller who receive the post request.
// Get request
$request = $this->get('request');
// Get files
$files = $request->files;
// Upload
$do = $service->upload($files);
Uploading from the dropzone (by drag and drop or click) is working and the uploads are successfull but using the myDropzone.addFile() function return me an empty object in my controller :
var_dump($files);
return
object(Symfony\Component\HttpFoundation\FileBag)#11 (1) {
["parameters":protected]=>
array(0) {
}
}
I think i don't setup correctly my var file in the save function.
I tryied to create JS image (var img = new Image() ...) but without any success.
Thanks for your help !
Finally i found a working solution without creating canvas :
function dataURItoBlob(dataURI) {
'use strict'
var byteString,
mimestring
if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
byteString = atob(dataURI.split(',')[1])
} else {
byteString = decodeURI(dataURI.split(',')[1])
}
mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]
var content = new Array();
for (var i = 0; i < byteString.length; i++) {
content[i] = byteString.charCodeAt(i)
}
return new Blob([new Uint8Array(content)], {type: mimestring});
}
And the save function :
function save(dataURI) {
var blob = dataURItoBlob(dataURI);
myDropzone.addFile(blob);
}
The file appears correctly in dropzone and is successfully uploaded.
I still have to work on the filename (my document is named "blob").
The dataURItoBlob function have been found here : Convert Data URI to File then append to FormData
[EDIT] : I finally wrote the function in dropzone to do this job. You can check it here : https://github.com/CasperArGh/dropzone
And you can use it like this :
var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAmAAAAKwCAYAAA...';
myDropzone.addBlob(dataURI, 'test.png');
I can't comment currently and wanted to send this to you.
I know you found your answer, but I had some trouble using your Git code and reshaped it a little for my needs, but I am about 100% positive this will work for EVERY possible need to add a file or a blob or anything and be able to apply a name to it.
Dropzone.prototype.addFileName = function(file, name) {
file.name = name;
file.upload = {
progress: 0,
total: file.size,
bytesSent: 0
};
this.files.push(file);
file.status = Dropzone.ADDED;
this.emit("addedfile", file);
this._enqueueThumbnail(file);
return this.accept(file, (function(_this) {
return function(error) {
if (error) {
file.accepted = false;
_this._errorProcessing([file], error);
} else {
file.accepted = true;
if (_this.options.autoQueue) {
_this.enqueueFile(file);
}
}
return _this._updateMaxFilesReachedClass();
};
})(this));
};
If this is added to dropzone.js (I did just below the line with Dropzone.prototype.addFile = function(file) { potentially line 1110.
Works like a charm and used just the same as any other. myDropzone.addFileName(file,name)!
Hopefully someone finds this useful and doesn't need to recreate it!
1) You say that: "Once the client have finished his job, he just have to click a save button which call the save function:"
This implies that you set autoProcessQueue: false and intercept the button click, to execute the saveFile() function.
$("#submitButton").click(function(e) {
// let the event not bubble up
e.preventDefault();
e.stopPropagation();
// process the uploads
myDropzone.processQueue();
});
2) check form action
Check that your form action="/upload" is routed correctly to your SF controller & action.
3) Example Code
You may find a full example over at the official Wiki
4) Ok, thanks to your comments, i understood the question better:
"How can i save my base64 image resource with dropzone?"
You need to embedd the image content as value
// base64 data
var dataURL = canvas.toDataURL();
// insert the data into the form
document.getElementById('image').value = canvas.toDataURL('image/png');
//or jQ: $('#img').val(canvas.toDataURL("image/png"));
// trigger submit of the form
document.forms["form1"].submit();
You might run into trouble doing this and might need to set the "origin-clean" flag to "true". see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#security-with-canvas-elements
how to save html5 canvas to server
I want to download multiple files on click of a button in jsp.
I am using the following code in the js to call one servlet twice.
var iframe = document.createElement("iframe");
iframe.width = iframe.height = iframe.frameBorder = 0;
iframe.scrolling = "no";
iframe.src = "/xyz.jsp?prodId=p10245";
document.getElementById("iframe_holder").appendChild(iframe);
var iframe2 = document.createElement("iframe");
iframe2.width = iframe2.height = iframe2.frameBorder = 0;
iframe2.scrolling = "no";
iframe2.src = "/xyz.jsp?prodId=p10243";
document.getElementById("iframe_holder").appendChild(iframe2);
In xyz.jsp i am calling the servlet which downloads the file from a path and send it on the browser.
Issue is that it is working safari,firefox but not in IE.
We cannot download multiple files with IE?
By design, non-user-initiated file downloads are blocked in IE. That inherently means that it should not be possible to download more than one file as the result of a single user-click.
I've used the following code to download multiple files in IE and Chrome
function downloadFile(url)
{
var iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.display = "none";
document.body.appendChild(iframe);
}
function downloadFiles(urls)
{
downloadFile(urls[0]);
if (urls.length > 1)
window.setTimeout(function () { downloadFiles(urls.slice(1)) }, 1000);
}
You pass an array of URLs to the downloadFiles() function, which will call downloadFile() for each with a short delay between. The delay seems to be the key to getting it to work!
I had a similar need but also wanted the downloads to occur in a new window.
I created a js to download a list of files, and a php to do the actual file saving. I used the above as a starting point, and the PHP start from (okay, can't find the original source). I encode the passed URI so spaces in the file names don't cause troubles.
(function () {
"use strict";
var files = [], // Array of filename strings to download
newWindow, // New window to handle the download request
secondsBetweenDownloads; // Wait time beteen downloads in seconds
//
// Download a file using a new window given a URI
//
function downloadFile(uri) {
if (!newWindow) {
newWindow = window.open('',
'',
'width=1500 height=100');
}
if (newWindow) {
newWindow.location =
'saveAs.php?' +
'file_source=' + encodeURI(uri);
newWindow.document.title = "Download File: " + uri;
} else {
console.log("Unable to open new window. Popups blocked?");
}
}
//
// Download all files specified in the files[] array from siteName.
// Download the file at array position zero, then set a timeout for
// secondsBetweenDownloads seconds
//
function downloadFiles(siteName) {
var showTime = new Date();
console.log(
showTime.toTimeString().substring(0,8) +
" Starting download for: " + files[0]
);
// Skip any empty entries, download this file
if (files[0].length > 0) downloadFile(siteName + files.splice(0, 1));
if (files.length > 0) { // If more files in array
window.setTimeout(function () { // Then setup for another iteration
downloadFiles(siteName );
}, secondsBetweenDownloads * 1000); // Delay for n seconds between requests
} else {
newWindow.close(); // Finished, close the download window
}
}
//
// Set the web site name and fill the files[] array with the files to download
// then kick off the download of the files.
//
$(document).ready(function () {
var
siteName** = "http://www.mysteryshows.com/thank-you/";
secondsBetweenDownloads** = 35; // N seconds delay between requests
files = [
"show1.mp3",
"show2.mp3"
];
downloadFiles(siteName, files);
});
}());
The HTML for the page is simple. Basically any syntax-compliant page will do.
The saveAs.php page which the js file uses in the newWindow.location line is php only.
<?php
if (isset($_GET['file_source'])) {
$fullPath = $_GET['file_source'];
if($fullPath) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment;
filename=\"".$path_parts["basename"]."\""); // use 'attachment' to
// force a download
header("Content-type: application/pdf"); // add here more headers for
// diff. extensions
break;
default;
header("Content-type: **application/octet-stream**");
header("Content-Disposition:
filename=\"".$path_parts["basename"]."\"");
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
$request = $path_parts["dirname"] . '/' .
rawurlencode($path_parts["basename"]);
readfile($request);
exit;
}
}
?>
I used rawurlencode on just the 'basename' portion of the URI to ensure it was a valid, encoded request.
It can be done by creating a blob using the file source URL. I have tested this with image and PDF files in IE 11.
if (navigator.msSaveBlob) {
var xhr = new XMLHttpRequest();
xhr.open('GET', file_url, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
navigator.msSaveBlob(blob, file_name);
}
}
xhr.onerror = function(e) {
alert("Error " + e.target.status + " occurred while receiving the document.");
}
xhr.send();
}
I got this idea when I came across this: Getting BLOB data from XHR request