I come here because I use the CameraPreview class from ionic-native in my ionic 2 project to take a picture, and I actually struggle with the path of the picture which is something like : assets-library://asset/asset.JPG?id=...
That type of URL is obviously impossible to render in the DOM, and I want to know how to convert it into a supported URL for the img or ion-img tag.
I tried to convert it using File.readAsDataURL() as it is suggested in the following links, but the promise return an empty string.
https://www.npmjs.com/package/cordova-camera-preview
http://ionicframework.com/docs/v2/native/file/
You can load it via http as a Blob and then set that as the src for an img.
Example below:
this.http.get(fileURI, new RequestOptions({responseType:ResponseContentType.Blob}))
.subscribe(
data => {
var blob = data.blob();
this.previewImage = this.sanitize(URL.createObjectURL(blob));
this.cd.detectChanges();
});
Make note of the sanitize function. This is required to bypass default browser security - see https://stackoverflow.com/a/37432961/3446442
In this example the img tag is bound to the previewImage variable:
<div [style.width.px]="cameraSize" [style.height.px]="cameraSize">
<img id="preview" [src]="previewImage">
</div>
Related
I need to upload image and video files to the server in an Angular application using Laravel 5.1 as the back end. All Ajax requests need to go to the Laravel controller first, and we have the code there for how the file gets handled when it gets there. We have previously done normal HTML forms to submit file uploads to the controller, but in this case we need to avoid the page refresh of a form, so I am attempting this in Ajax through Angular.
What information do I need to send to the Laravel controller with Ajax that was being sent to the controller via an HTML form previously?
This is the code in the Laravel controller that handled the file information once it got there. That's what I need to figure out how to send, so I can hopefully reuse this code:
$promotion = Promotion::find($id);
if (Input::hasFile('img_path')){
$path = public_path().'/images/promotion/'.$id.'/';
$file_path = $path.'promotion.png';
$delete = File::delete($file_path);
$file = Input::file('img_path');
$uploadSuccess = $file->move($path, 'promotion.png');
$promotion->img_path = '/images/promotion/'.$id.'/promotion.png';
}
if (Input::hasFile('video_path')){
$path = public_path().'/video/promotion/'.$id.'/';
$file_path = $path.'promotion.mp4';
$delete = File::delete($file_path);
$file = Input::file('video_path');
$uploadSuccess = $file->move($path, 'promotion.mp4');
$promotion->video_path = '/video/promotion/'.$id.'/promotion.mp4';
}
As you can see above, we are converting whatever file we get to a PNG with the file name promotion.png so it's easy to fetch, and we are only accepting .mp4 video format. Because of that, we don't need to worry about checking if the file exists and is it ok to overwrite it. That's why you can see in the code we delete any existing file of that name before saving.
The HTML was just an input with a type of "file:
<input type="file" id="img_path" name="img_path" class="promo-img-path" accept="image/*">
We are using Angular now so I can't just send the above through an HTML form anymore. That's what I need to figure out how to do.
We are two developers just doing our best, so I'm sure there is a better way of doing this. However before I refactor this whole thing, I'm hoping I can use Angular (or jQuery as a last resort) to just send the controller whatever file data Laravel needs in order to make the above code work. The answer may be as simple as "send a PUT to the method in that controller above, but instead of a normal JSON payload, use file info in this format and you can gather that info with..."
I would also appreciate any tips on better ways I can do this in the future.
How to POST FormData Using the $http Service
When using the FormData API to POST files and data, it is important to set the Content-Type header to undefined.
var fd = new FormData()
for (var i in $scope.files) {
fd.append("fileToUpload", $scope.files[i]);
}
var config = {headers: {'Content-Type': undefined}};
var httpPromise = $http.post(url, fd, config);
By default the AngularJS framework uses content type application/json. By setting Content-Type: undefined, the AngularJS framework omits the content type header allowing the XHR API to set the content type. When sending a FormData object, the XHR API sets the content type to multipart/form-data with the proper boundaries and base64 encoding.
For more information, see MDN Web API Reference - XHR Send method
How did you get the file information into $scope.files?
How to enable <input type="file"> to work with ng-model
This directive also enables <input type="file"> to automatically work with the ng-change and ng-form directives.
angular.module("app",[]);
angular.module("app").directive("selectFilesNg", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" select-files-ng ng-model="fileArray" multiple>
<code><table ng-show="fileArray.length">
<tr><td>Name</td><td>Date</td><td>Size</td><td>Type</td><tr>
<tr ng-repeat="file in fileArray">
<td>{{file.name}}</td>
<td>{{file.lastModified | date : 'MMMdd,yyyy'}}</td>
<td>{{file.size}}</td>
<td>{{file.type}}</td>
</tr>
</table></code>
</body>
RECOMMENDED: POST Binary Files Directly
Posting binary files with multi-part/form-data is inefficient as the base64 encoding adds an extra 33% overhead. If the server API accepts POSTs with binary data, post the file directly.
See How to POST binary files with AngularJS (with DEMO)
I've created a new React application. As it stands, it just the template from Visual Studio; New Project -> Asp.Net Core -> React.
When the application runs, there is an element of dynamic content displayed on the screen. What I want to be able to do is to get some kind of HTML dump of this page, such that I could paste it into a static web application and have the same screen rendered.
I've had a look around, and have found a few tools, such as react-snapshot which appear to do what I want; however, it seems to be that you're in or out; that is, you either have it dynamically rendered or statically rendered. I just want a static dump of the HTML, and would like to leave the rendering as is.
For example, inside my Javascript, I have the following code:
const htmlSection = document.getElementById("MyHtml");
// Export Html Here
Is this kind of thing possible and, if so, how can it be achieved in code?
I did like this
const handleExport = () => {
const link = document.createElement("a");
// Create a blog object with the file content which you want to add to the file
const file = new Blob([document.getElementsByTagName('html')[0].innerHTML], { type: 'text/plain' });
// Add file content in the object URL
link.href = URL.createObjectURL(file);
// Add file name
link.download = "sample.html";
// Add click event to <a> tag to save file.
link.click();
URL.revokeObjectURL(link.href);
}
The HTML and module style can be exported, but the problem is that is javascript event can not be remained anymore.
You can use the fs module to read your index file something like this:
fs.readFileSync(path[, options])
I am trying to download a server side generated pdf file in client, which i get with axios and save it in redux and using FileSaver to download it.
const getTicketPdf = ({ userID, ticketID }) =>
requestApi(`/users/${userID}/tickets/${ticketID}/pdf`, {
method: 'get',
});
requestApi gets me all neccessary headers so that i can download the file.
the data is then stored in redux like this:
data: "%PDF-1.4\n3 0 obj\n<</Type /Page\n/Parent 1 0 R\n/MediaBox [0 0 595.00 842.00]\n/Resources 2 0 R\n/Contents 4 0 R>>\nendobj\n4 0 obj\n<</Filter /FlateDecode /Length 64>>\nstream\nx�3R��2�35W(�*T0P�R0T(\u0007�Y#�\u000e��#Q…"
i call it in render with:
<div>
<button onClick={ () => this.getPdf(ticket) }>PDF</button>
</div>
getPdf = ticket => {
const blob = new Blob([ticket]);
FileSaver.saveAs(blob, 'Ticket.pdf');
}
I am always getting the following error:
TypeError: Cannot read property 'saveAs' of undefined
i tried also to set
responseType: 'blob'
but this doesn't help either.
Next thing I testet was with react-pdf library, where I managed to display pdf in Component, but i cant print it. User should only habe to save it and then print it locally (or at least show it in separate tab as PDF, which i tried with window.open() as base64 encoded string).
How can I download a server side generated PDF otherwise? Are there any better ways?
Unfortunately I have to set HTTP Headers in order to get that file.
Thanks in advance.
The error stems from the fact that there is no FileSaver object (or rather, it's non-standard).
It seems to be polyfilled by this third-party library: https://github.com/eligrey/FileSaver.js
The error you are seeing is caused by a reference to an undefined variable FileSaver - I guess that you are using FileSaver.js, and need to fix the import. You should also bear in mind that FileSaver is deprecated in favour of the download attribute. See this answer for details on how to use it.
Either way, in the interests of keeping your store light, you should save a reference to the PDF in your Redux store, rather than the string itself.
I am trying to append the recorded video which is blob object into quill editor but the video which is appended in the editor is not playable.
Able to see only the blob object getting printed in the quill editor. If i try to open the contents in the browser it is working fine. Any suggestions?
enter image description here
well,according to this issue,
I think you maybe need to overwrite the video module's sanitize method to make it work,for image it can work like this:
var Image = Quill.import('formats/image')
Image.sanitize = function(url) {
return url
}
so as I guess, following things maybe useful:
var Video = Quill.import('formats/video')
Video.sanitize = function(url) {
return url
}
and you may need provide blob url to make it work
I want to display menus which can be image as well as pdf .
I am using ng-pdfviewer to achieve this . My controller code is ::
venueApp.controller('venueController',['$scope',PDFViewerService',function($scope,pdf){
$scope.viewer = pdf.Instance("viewer");
$scope.pageLoaded = function(curPage, totalPages) {
$scope.currentPage = curPage;
$scope.totalPages = totalPages;
};
$scope.nextPage = function() {
$scope.viewer.nextPage();
};
$scope.prevPage = function() {
$scope.viewer.prevPage();
};
}]);
and my html code is ::
<a id="image_{[ menu.id ]}" ng-if="menu.filename.indexOf('.pdf') > -1">
<button ng-click="prevPage()"><</button>
<button ng-click="nextPage()">></button>
<br>
<span>{[currentPage]}/{[totalPages]}</span>
<br>
<pdfviewer src="{[menu.menu_url]}" on-page-load='pageLoaded(page,total)' id="viewer"></pdfviewer>
</a>
I am using {[]} for expression evalutaion because i configured it to . Now in my console , the plugin is outputting the correct messages i guess
Printed in console by this plugin
src attribute changed, new value is https://d1hpn7r5i0azx7.cloudfront.net/uploads/menu/18/ankush.pdf
loadPDF https://d1hpn7r5i0azx7.cloudfront.net/uploads/menu/18/ankush.pdf
Warning: Deprecated API usage: getDocument is called with pdfDataRangeTransport, passwordCallback or progressCallback argument -- printed by pdf.js
But the pdf is not being painted . My DOM element for the padf viewer tag is ::
<pdfviewer src="https://d1hpn7r5i0azx7.cloudfront.net/uploads/menu/18/ankush.pdf" on-page-load="pageLoaded(page,total)" id="viewer" class="ng-isolate-scope"><canvas></canvas></pdfviewer>
I dont understand what is the issue . Maybe it is with the pdf file as chrome also does not display it , instead just downloads it . the link for the sample pdf is ::
https://d1hpn7r5i0azx7.cloudfront.net/uploads/menu/18/ankush.pdf
Also i am posting this question in SO instead of just posting it in the github plugin page because i seriously think it has to do something with the pdf file instead od the plugin .
P.S it is not my CV , just took one from the pool of applicants in our company :P
I have used http://viewerjs.org/ for offline pdf with angular. But here it seems you have online pdf path . So why are you not trying google document viewer ? It is best for online documents.
Please look at following link:
https://docs.google.com/gview?url=http://infolab.stanford.edu/pub/papers/google.pdf
you need to change url parameter with your path.
Also you can use this link in your website with iframe as following:
<iframe src="http://docs.google.com/gview?url=http://infolab.stanford.edu/pub/papers/google.pdf&embedded=true" style="width:600px; height:500px;" frameborder="0"></iframe>