Blob as source docx/pptx/xlsm/etc as iframe - javascript

I am having a problem identical to this enter link description here (unanswered) question. Is it possible to create an iframe of docx/pptx/xlsm/etc with a blob? For reference, here's some code
AngularJS snippet to have docx iframes
get_file_data().then(function(response){ //assume get_file_data works
memtype = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
var blob = new Blob([response.data], {type: memtype});
var blob_url = $window.URL.createObjectUrl(blob);
var office_url = "http://view.officeapps.live.com/op/embed.aspx?src=";
var url = office_url + blob_url;
$scope.content = $sce.trustAsResourceUrl(url);
And then in my html file:
<iframe ng-src = "{{content}}"> </frame>
It doesn't work likely because blob_url has blob:// as a prefix, how can I fix this to make it work? Or is this something that can't be done? For some reason, this approach works for pdf files

Related

How to save pdf file from Firebase in local folder from web

How do I download and save a pdf file from Firebase storage.
During upload I save upload infomation on real time firebase node like this:
while my storage is as follow:
My save btn is linked to this function:
function savepdfFile(){
let selectedGroup = document.getElementById("groupname");
let selectedDate = document.getElementById("dateId");
let selectedGroupValue = selectedGroup.value;
let selectedDateValue = selectedDate.value;
let mdate = "";
mdate = changeDateForamat(selectedDateValue);
downloadPDFDoc(selectedGroupValue,mdate);
}
I retrieve information of this pdf file from firebase real time node as follow when a save button is clicked;
function downloadPDFDoc(groupname,mdate){
let pdfName, pdfUrl;
firebase.database().ref('SessionPDFStorage').once('value',function(snapshot){
snapshot.forEach(
function(ChildSnapshot){
//let mLocation = ChildSnapshot.val().province;
let mGroup = ChildSnapshot.val().selectedGroup;
let mydate = ChildSnapshot.val().currentDate;
let ddate = changeDateForamat(mydate);
if(groupname == mGroup && mdate == ddate){
pdfName = ChildSnapshot.val().fileName;
pdfUrl = ChildSnapshot.val().fileImageUri;
}
}
);
loadScannedImage(pdfName,pdfUrl);
});
}
How do I develop the loadScannedImage(pdfName,pdfUrl) funtion below to using the above information to save the file on the local folder dynamically? example automatically save this pdf to a local c:\download directory.
function loadScannedImage(pdfName,pdfUrl){
}
I have seen some implementation of FileSaver.js and Blob.js but it is not quite clear how I would use them.
Any help will be appreciated.
I created an anchor element and pass both pdf name and its url link as as attributes follow inside loadscnnedImage:
function loadScannedImage(pdfName,ImgUrl){
var element = document.createElement('a');
element.setAttribute('href',`${ImgUrl}`);
element.setAttribute('download', pdfName);
document.body.appendChild(element);
element.click()
}
but I would have liked to dynamically safe the pdf file directly to browsers default downloaded folder on the machine. But this works too

Set Image src from image blob

I have trying to request an image from an API and set the src of an img in my web page. The API returns a blob that represents a .png file. At this time, I'm requesting the image using the following:
const fetchResult = await fetch(imageApiUrl);
const resultBlob = await fetchResult.blob();
console.log(resultBlob);
In the console, I can see:
Blob {size: [some number], type: "image/png" }
So, I know that I have a result. I assume a blob. I now need to set this blob as the source of an img in my HTML, which looks like this:
<img id="profilePicture" alt="Profile Picture" height="250" width="250" />
I have this:
var profilePicture = document.getElementById('profilePicture');
How do I set the src of the profilePicture element to the blob?
You could use URL.createObjectURL in order to create a temporary URL that points to the in-memory image:
let url = URL.createObjectURL(resultBlob);
const img = document.getElementById('profilePicture');
img.src = url;

Get src type of img or video tag (not extension)?

Say I have an image tag such as this:
<img src="smiley.gif" alt="Smiley face" height="42" width="42">
I know I can get the src by using myImageEl.src.
However, how do I get the type of the src (.gif in this case)?
Basically, my end goal is to pass the file type to window.URL.createObjectUrl()
let src = imageEl.src;
let srcType = src.type; // Here I need to get the type
let videoFile = new Blob([src], {type: srcType});
let videoSrc = window.URL.createObjectURL(videoFile);
var imgSrc = 'image.jpeg';
var ext = imgSrc.replace(/^.*\./, '')
I am not very good with regex, but using regex to fetch the extension of the image or video is the a good way of accomplishing this task.
For precision sake you could compare ext with a predeifined set of array
imgTag = ['jpg', 'jpeg', 'gif', 'png'];
vidTag = ['mp4', '3gp']
then you can compare using a forEach loop
From your tags I noticed you want to access image source type from javascript, if so you can use following codes base on what attributes we have for that image element:
for example if image element has id :
var imageElement = document.getElementById(id);
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();
imgType will be the type of your image.
And if your image element doesn't have id, you can use document.getElementsByTagName("img") instead of document.getElementById(id) and code will look like this
var imageElement = document.getElementsByTagName("img");
var imgsrc = imageElement.src;
var imgType = imgsrc.split('.').pop();

Convert hexadecimal string to Blob and display PNG image with AngularJS

I got a web page (I/m using angularjs 1.4.8) and I'm trying to show an image which comes from my GET url request.
Here is the page code (I got a grid and I/m displaying previews if they are applicable):
<div ng-show="message.message == null && message.is_image != null">
<a href="#" ng-click="downloadFile(message.id_message)">
<img data-ng-src="data:image/{{message.image_resolution}};base64,{{message.image_preview}}"/>
</a>
</div>
So, I got cassandra DB with this blob field and my Json looks like:
created_date:"2017-03-31 22:05:42.284Z"
id_message:"e6e2a5cb-ec25-472f-a59b-3f16a3a8afa9"
id_user_link:"47ed65bf-5520-4901-88c8-01980ffbcd4d"
id_user_sent:"3495c2de-c93c-4323-8e48-1fcecbfde625"
image_length:174443
image_name:"5.png"
image_preview:"0x89504e470d0a1a0a0000000d49484452000007800000039a080600000079a04f28000038714944415478daecd9496e55570045d13bfff124d442c654016320c4d4219832046308a132087199c26ba4f1fed65ad29ec0e99e71ec97635392244992244992244992b4f90d23489224499
...
... some other 90 lines of symbols
...
00000108401d8006c0096244906600000000008c2006c0036004b922403300000000004610036001b802549920118000000008230001b800dc09224c9000c000000004118800dc00660499264000600000080200cc0066003b024493200030000004010066003b001589224198001000000200803b001d8002c49920cc000000000108401d8006c0096244906600000000008c2006c0036004b92a4ff95fe0ffc7d46dd1b63a2b10000000049454e44ae426082"
image_resolution:"png"
is_image:1
message:null
But I have no images in my web page (only icon of broken link to image):
I researched
Angularjs showing image blob
Display blob image in html with angularjs
AngularJS - Show byte array content as image
but this won't help.I tried some varieties of this code:
page:
<img data-ng-src="data:image/{{message.image_resolution}};base64,{{b64encoded(message.image_preview)}}"/>
js:
$scope.b64encoded = function(image_preview){
//btoa(String.fromCharCode.apply(null, response.data[0].ClassImage.data));
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image_preview\//);
return btoa(String.fromCharCode.apply(null, image_preview));
}
RESOLVED
Finally, that was not the issue about AngularJS or blob - that was a Java issue:
byte[] previewSizeByte = baos.toByteArray(); and I stored this one as blob, so, now I got a text field and my Java code looks like (I decided to use BufferedImage for preview):
String base64String = imgToBase64String(preview, fileFormat);
and
private String imgToBase64String(BufferedImage preview, String fileFormat) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(preview, fileFormat, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
I really appreciate stackoverflow members for their comments and answers, they were extremely helpful
It appears that the CassandraDB is sending the image data as a hexadecimal string. It would be more efficient to send it as a base64 string and it would be easier to use.
Here is a function to convert a hexadecimal string to an image/png Blob and display the image:
angular.module("myApp",[]).controller("myVm", function($scope) {
var vm = $scope;
var testHex =
["0x89504e470d0a1a0a0000000d494844520000003c00000028040300000050",
"9584cc0000001b504c5445000000ffffff1f1f1f7f7f7f3f3f3f9f9f9f5f",
"5f5fdfdfdfbfbfbf2cb790f6000000097048597300000ec400000ec40195",
"2b0e1b000000b749444154388ded90cf0a83300cc63faaf5394a5defc56c",
"ee2a0c760e2a3b0b6e3ec7c0175f5aff1e77da657ea40dcd2ff90a010efd",
"9772a2f3f6ea4b830e121915b1a04e859999066a4b1801562dec544c3d36",
"cc723506ac9791809538f564af54055c33f8861d76d0cacfd30efc9450c3",
"b0e20189e28847aac5397458b7e2175d4cde4ed37252cff7d83ce367c849",
"b56014ecf638fa28bf62cd49b7c3e9a384f86764269cbde5bf665b969230",
"31adb25feffdd02ff50109f91bbd7897f34a0000000049454e44ae426082"]
.join('');
vm.hex = testHex;
vm.imgUrl = URL.createObjectURL(toPngBlob(testHex));
function toPngBlob(str){
var hexStr = str.slice(2);
var buf = new ArrayBuffer(hexStr.length/2);
var byteBuf = new Uint8Array(buf);
for (let i=0; i<hexStr.length; i+=2) {
byteBuf[i/2] = parseInt(hexStr.slice(i,i+2),16);
}
var blob = new Blob([byteBuf], {type: "image/png"});
return blob;
};
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myApp" ng-controller="myVm">
<h1>Convert hex string to PNG Blob</h1>
{{hex}}<br>
{{imgUrl}}<br>
<img ng-src="{{imgUrl}}">
</body>

Passing image data to another page

I'm trying to access a camera and a photo album on a mobile device and get the chosen image. I did that with the code below. My problem is, it generates image data, and I have to transfer that to another page, but because of the size of the generated string, I can't use URL parameters. It shows me the error: [404] Request-URI Too long. How can I pass the information to the other page?
Here is the code: http://jsfiddle.net/8u426/
The JS:
<script>
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
document.getElementById("fotoImg").src = oFREvent.target.result;
document.getElementById("fotoImg").style.visibility = "visible";
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
document.getElementById("fotoImg").style.height = screenHeight;
document.getElementById("stringImg").innerText = "Data Image: " + oFREvent.target.result;
};
$(function() {
$("input:file").change(function (){
var input = document.querySelector('input[type=file]');
var oFile = input.files[0];
oFReader.readAsDataURL(oFile);
});
});
</script>
Update:
The problem is: if I try to open a new page passing the Data Image string as a parameter in the URL (with "?"). The new page will show the 404 error that I mentioned, because the string is too long.
Try changing your form to
<form id="form1" method="POST" action="[Page2 URL]">
<input id="filePic" type="file" name="image" accept="image/*" capture />
</form>
where [Page2 URL] is the URL for page to receive the image uploaded.
And JavaScript to
oFReader = new FileReader();
oFReader.onload = function (oFREvent) {
var screenHeight = screen.availHeight;
screenHeight = screenHeight - 220;
var img = $('#fotoImg');
img.attr('src', oFREvent.target.result);
img.css( { height : screenHeight, visibility: 'visible' });
$("#stringImg").text( "Data Image: " + oFREvent.target.result);
$('#form1').submit();
};
$(function() {
$("input:file").change(function (){
var oFile = this.files[0];
oFReader.readAsDataURL(oFile);
});
});
I couldn't make work with php (considering that I didn't want to work with php) and html forms (methods get and post)... So I used the jQuery library called "jQuery Storage".
It was easy, on the page that I select the image you shoud use:
$.sessionStorage([key],[value]);
So, was like that:
$.sessionStorage('chosenImg', document.getElementById("photoImg").src);
And in the new page, to get the value, just add in the code:
$.sessionStorage('chosenImg');
Of course, I had to download de .js library from the website and add the line below on both html pages:
<script src="jquery.storage.js"></script>
The only inconvenient it is a little heavy for mobile, but was the only way I found...
That is it! Thanks everyone!
dataimage base64 data image

Categories