Upload any text file and preview using only HTML5 and AngularJS - html

How to upload document of any type like .txt, jpeg or gif and get preview in html page? Only by using HTML5 and AngularJS. No need to save document at any location.

You can use the FileReader API to read the data in the file.
This example modifies the above linked answer and checks if the file type is an image and displays it as such. Otherwise, it displays the file's data as text.
angular.module('fileLoad', []).directive('fileSelect', ['$window', function($window) {
return {
restrict: 'A',
require: 'ngModel',
link: function($scope, el, attr, ctrl) {
var fileReader = new $window.FileReader();
var fileType;
fileReader.onload = function() {
var fileData = {};
fileData.type = fileType;
fileData.data = fileReader.result;
ctrl.$setViewValue(fileData);
$scope.$apply();
};
el.bind('change', function(e) {
var fileName = e.target.files[0];
fileType = (fileName && fileName.type) || '';
if (fileType.indexOf('image') != -1) {
fileReader.readAsDataURL(fileName);
} else if(fileName) {
fileReader.readAsText(fileName);
} else {
ctrl.$setViewValue({});
$scope.$apply();
}
});
}
};
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fileLoad">
<input type="file" ng-model="file.data" file-select>
<img ng-show="file.data.type && file.data.type.indexOf('image') != -1" data-ng-src="{{file.data.data}}" />
<p ng-show="file.data.type && file.data.type.indexOf('image') == -1" ng-bind="file.data.data"></p>
</div>

Related

Angular - (File) input works irregular on file select

Angular v 9.0.7
i have this input in my html which is gets triggered by the button:
<input #file (change)="importFile($event)" accept="audio/*, image/*, video/*" hidden type="file">
<button class="msg-npt-btn msg-npt-fl-icon" (click)="file.click()"></button>
it works for the first time i select a file but after that importFile() get called every second or third time if i select another file.
importFile(event) {
alert("import"); //test
if (event.target.files.length == 0) {
console.log("No file selected!");
return
}
this.selectedFile = event.target.files[0];
...
This is example how to load images may will it help.
importFile(event): void {
alert('import'); // test
const reader = new FileReader();
if (event.target.files.length === 0) {
console.log('No file selected!');
return;
}
reader.readAsDataURL(event.target.files[0]);
reader.onload = ((r) => {
this.selectedFile = r.target.result;
});
}

how to show pdf file in ionic app with out download

Things i did :
used inappbrowser
used google doc
used webview
so i have tried all these methods to show the pdf file in android device using ionic. But no use, i can see the download button in all these methods. Can any one tell me how can i display pdf without download option for user.
my code :
<div class="col col-50 clsGrid" ng-click="showFile('http://www.orimi.com/pdf-test.pdf')">
</div>
my pdf file :
http://www.orimi.com/pdf-test.pdf
My JS :
$scope.showModal = function(templateUrl) {
$ionicModal.fromTemplateUrl(templateUrl, {
scope: $scope,
animation: 'slide-in-up'
}).then(function(modal) {
$ionicLoading.show({
duration: 1000
});
$scope.modal = modal;
$scope.modal.show();
});
}
// Close the modal
$scope.closeModal = function() {
$scope.modal.hide();
$scope.modal.remove()
};
$scope.showFile = function(FileUrl) {
var file = FileUrl;
console.log(file);
//var openurl = cordova.InAppBrowser.open(file, '_blank');
// var openurl = cordova.InAppBrowser.open(file,'_blank', 'location=yes');
// var openurl = cordova.InAppBrowser.open("https://docs.google.com/viewer?url=" + file, '_blank');
// var openurl = cordova.InAppBrowser.open('https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true', '_blank');
//window.open("https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true",'_blank');
var openurl = cordova.InAppBrowser.open('https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true&toolbar=0&navpanes=0&scrollbar=0', '_blank');
}
I tried all ways. But not able to find the solution.If any one know it will be usefull.If any expert in this, i can send my demo project for reference .
Thanks in advance !
You will need to use ng-pdfviewer.
AngularJS PDF viewer directive using pdf.js.
<button ng-click="prevPage()"><</button>
<button ng-click="nextPage()">></button>
<br>
<span>{{currentPage}}/{{totalPages}}</span>
<br>
<pdfviewer src="test.pdf" on-page-load='pageLoaded(page,total)' id="viewer"></pdfviewer>
and in your AngularJS code:
var app = angular.module('testApp', [ 'ngPDFViewer' ]);
app.controller('TestCtrl', [ '$scope', 'PDFViewerService', function($scope, pdf) {
$scope.viewer = pdf.Instance("viewer");
$scope.nextPage = function() {
$scope.viewer.nextPage();
};
$scope.prevPage = function() {
$scope.viewer.prevPage();
};
$scope.pageLoaded = function(curPage, totalPages) {
$scope.currentPage = curPage;
$scope.totalPages = totalPages;
};
}]);

How to open PDF file on ng-click instead of downloading in Angularjs?

I am able to download the file when user clicked on this link "Click to get your file". But now I need to open the PDF file (like modal window) and restrict the user from downloading the file.
My Controller
var resumeJson = {
"json":{
"request":{
"candidateid":$rootScope.globals.currentUser.userId,
"type":2
}
}
};
$scope.getResume = function() {
console.log(JSON.stringify(resumeJson));
$scope.resume = UserService.getFile(resumeJson);
console.log($scope.resume);
}
My Html
<div class="grid_3" ng-show="resumeflag==true || uploaded==true" ng-hide="resumeflag==false || uploaded==false">
<a ng-click="getResume()" href="{{resume}}">
<img ng-src="images/resume.png" style="height:4em; width:4em;" ng-click="getResume()" href="{{resume}}">Click to get Your Resume</a>
</div>
What about an iframe?
Controller:
$scope.getResume = function() {
UserService.getFile(resumeJson)
.then(function(response) {
var file = new Blob([response], {type: 'application/pdf', charset:'utf-8'});
var fileURL = URL.createObjectURL(file);
$scope.resume = $sce.trustAsResourceUrl(fileURL);
});
}
HTML:
<iframe id="resume" src="{{resume}}" onload="setSize()"></iframe>
<script type="text/javascript">
function setSize() {
document.getElementById('resume').style.height = '100%';
document.getElementById('resume').style.width = '100%';
}
</script>

Validate height width with bootstrap validator

$('#ad_pd_form').bootstrapValidator({
fields: {
ad_pd_image: {
validators: {
file: {
extension: 'jpg,png',
type: 'image/jpg,image/png',
maxSize: 30(Height) * 30 (width),
message: 'The selected file is not valid'
}
}
}
}
});
Friends i'm validating an image in bootstrap validator , I have to validate the height and width of the uploaded image , how to achieve this concept by using bootstrap validator . I need to upload only the image with size of 30 * 30 .
You Need to Suppurate validation function for the Image upload Check Dimension.
Here is the Sample Code:
$(function () {
$("#upload").bind("click", function () {
//Get reference of FileUpload.
var fileUpload = $("#fileUpload")[0];
//Check whether the file is valid Image.
var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:])+(.jpg|.png|.gif)$");
if (regex.test(fileUpload.value.toLowerCase())) {
//Check whether HTML5 is supported.
if (typeof (fileUpload.files) != "undefined") {
//Initiate the FileReader object.
var reader = new FileReader();
//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {
//Initiate the JavaScript Image object.
var image = new Image();
//Set the Base64 string return from FileReader as source.
image.src = e.target.result;
image.onload = function () {
//Determine the Height and Width.
var height = this.height;
var width = this.width;
if (height > 100 || width > 100) {
alert("Height and Width must not exceed 100px.");
return false;
}
alert("Uploaded image has valid Height and Width.");
return true;
};
}
} else {
alert("This browser does not support HTML5.");
return false;
}
} else {
alert("Please select a valid Image file.");
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="file" id="fileUpload" />
<input id="upload" type="button" value="Upload" />

upload image from local into tinyMCE

tinyMCE has an insert image button, but how to handle its functionality
pls give some code
I have upvoted the code written by #pavanastechie, but I ended up rewriting it quite a lot. Here's a version that is far shorter, which might have value to some people
tinymce.init({
toolbar : "imageupload",
setup: function(editor) {
var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
$(editor.getElement()).parent().append(inp);
inp.on("change",function(){
var input = inp.get(0);
var file = input.files[0];
var fr = new FileReader();
fr.onload = function() {
var img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
inp.val('');
}
fr.readAsDataURL(file);
});
editor.addButton( 'imageupload', {
text:"IMAGE",
icon: false,
onclick: function(e) {
inp.trigger('click');
}
});
}
});
NOTE: this relies on jquery, and won't work without it. Also, it assumes that the browser supports window.FileReader, and doesn't check for it.
I used pavanastechie's and Chris Lear's solutions, which worked perfectly for me, and wanted to share a complete example built on theirs that uploads the image to the server and embeds the image using the URL provided back by the server:
tinymce.init({
toolbar: 'imageupload',
setup: function(editor) {
initImageUpload(editor);
}
});
function initImageUpload(editor) {
// create input and insert in the DOM
var inp = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
$(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
editor.addButton('imageupload', {
text: '',
icon: 'image',
onclick: function(e) { // when toolbar button is clicked, open file select modal
inp.trigger('click');
}
});
// when a file is selected, upload it to the server
inp.on("change", function(e){
uploadFile($(this), editor);
});
}
function uploadFile(inp, editor) {
var input = inp.get(0);
var data = new FormData();
data.append('image[file]', input.files[0]);
$.ajax({
url: '/admin/images',
type: 'POST',
data: data,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
},
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.responseText) {
errors = JSON.parse(jqXHR.responseText).errors
alert('Error uploading image: ' + errors.join(", ") + '. Make sure the file is an image and has extension jpg/jpeg/png.');
}
}
});
}
!!!!ENJOY!!! here is the solution to load directly from local computer
JSFIDDLE DEMO
<textarea name="content"></textarea>
<title>Local image loading in to tinymce</title>
<br/>
<b>Image size should be lessthan 500kb</b>
JAVA SCRIPT CODE
`
tinymce.init({
selector: "textarea",
toolbar: "mybutton",
setup: function(editor) {
editor.addButton('mybutton', {
text:"IMAGE",
icon: false,
onclick: function(e) {
console.log($(e.target));
if($(e.target).prop("tagName") == 'BUTTON'){
console.log($(e.target).parent().parent().find('input').attr('id'));
if($(e.target).parent().parent().find('input').attr('id') != 'tinymce-uploader') {
$(e.target).parent().parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
}
});
}
if($(e.target).prop("tagName") == 'DIV'){
if($(e.target).parent().find('input').attr('id') != 'tinymce-uploader') {
console.log($(e.target).parent().find('input').attr('id'));
$(e.target).parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
}
});
}
if($(e.target).prop("tagName") == 'I'){
console.log($(e.target).parent().parent().parent().find('input').attr('id')); if($(e.target).parent().parent().parent().find('input').attr('id') != 'tinymce-uploader') { $(e.target).parent().parent().parent().append('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files` property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createImage;
fr.readAsDataURL(file);
}
function createImage() {
img = new Image();
img.src = fr.result;
editor.insertContent('<img src="'+img.src+'"/>');
}
});
}
}
});
}
});
`
Din't try iManager but found tinyFCK good and easy to configure which gives CKEditor's filemanager integrated with TinyMCE
1.Download TinyFCK
2.replace filemanger folder in tinyFCK with filemanager folder of ur CKEditor
3.code :
-
tinyMCE.init({
theme : "advanced",
file_browser_callback : "fileBrowserCallBack",
});
function fileBrowserCallBack(field_name, url, type, win) {
var connector = "../../filemanager/browser.html?Connector=connectors/php/connector.php";
var enableAutoTypeSelection = true;
var cType;
tinyfck_field = field_name;
tinyfck = win;
switch (type) {
case "image":
cType = "Image";
break;
case "flash":
cType = "Flash";
break;
case "file":
cType = "File";
break;
}
if (enableAutoTypeSelection && cType) {
connector += "?Type=" + cType;
}
window.open(connector, "tinyfck", "modal,width=600,height=400");
}
I know this post is old, but maybe this will help someone trying to find a open source file manager for tinymce:
https://github.com/2b3ez/FileManager4TinyMCE
This worked great for me.
Based on #Chris Lear's answer, I have re-modified the script so that it supports multiple file uploads to server, and removed the data image for preview after content is posted and before table is updated with a little php script
tinymce.init({
selector: 'textarea',
setup: function(editor) {
var n = 0;
var form = $('#form_id'); // your form id
editor.addButton( 'imageupload', {
text:"IMAGE",
icon: false,
onclick: function(e) {
$(form).append('<input id="tinymce-uploader_'+n+'" class="tinymce-uploader" type="file" name="pic['+n+']" mutliple accept="image/*" style="display: none;">');
$('#tinymce-uploader_'+n).trigger('click');
n++;
$('.tinymce-uploader').on("change",function(){
var input = $(this).get(0);
var file = input.files[0];
var filename = file.name;
var fr = new FileReader();
fr.onload = function() {
var img = new Image();
img.src = fr.result;
editor.insertContent('<img data-name="'+filename+'" src="'+img.src+'"/>');
}
fr.readAsDataURL(file);
});
}
});
},
And on php side inside the upload php file:
function data2src($content, $img_path ='') {
preg_match('/data\-name="([^"]+)/i',$content, $data_name);
$tmp = preg_replace('/src=["]data([^"]+)["]/i', '', $content);
$content = preg_replace('/data\-name\=\"/i', 'src="'.$img_path, $tmp);
return $content;
}
I know it is an old question. However, I think this answer may help somebody who wants to upload multiple images by using tinyMCE 5.xx.
Based on #Chris Lear's and #stephen.hanson's answer, I modify some code to support multiple images uploading. Here is my code. Hope it could help somebody.
tinymce.init({
toolbar: 'imageupload',
setup: function(editor) {
initImageUpload(editor);
}
});
function initImageUpload(editor) {
// create input and insert in the DOM
var inp = $(`<input id='tinymce-uploader' type='file' name='pic' accept='image/*' style='display:none' multiple>`);
$(editor.getElement()).parent().append(inp);
// add the image upload button to the editor toolbar
editor.addButton('imageupload', {
text:'IMAGE',
onAction: function(_) {
// when toolbar button is clicked, open file select modal
inp.trigger('click');
}
});
// when a file is selected, upload it to the server
inp.on('change',function(){
for(let i=0;i<inp[0].files.length;i++){
let file = inp[0].files[i];
let data = new FormData();
data.append('multipartFile',file);
axios.post('/upload/image/url',
data,
{
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(res => {
if (res.status = 200) {
editor.insertContent('<img class="content-img" src="' + data.url + '"/>');
// clear data to avoid uploading same data not working in the second time
inp.val('');
}
})
}
It works for image upload.Is this possible for file upload ? I want to add a custom file upload option from local into tinyMCE and want to show it by url .
Code is something like below which not working:
ed.addButton('mybutton2', {
text:"File",
icon: false,
onclick: function(e) {
console.log($(e.target));
if($(e.target).prop("tagName") == 'BUTTON'){
console.log($(e.target).parent().parent().find('input').attr('id'));
if($(e.target).parent().parent().find('input').attr('id') !=
'tinymce-uploader') {
$(e.target).parent().parent().append('<input id="tinymce-
uploader" type="file" name="pic" accept="*" height="100" weidth="100"
style="display:none">');
}
$('#tinymce-uploader').trigger('click');
$('#tinymce-uploader').change(function(){
var input, file, fr, img;
if (typeof window.FileReader !== 'function') {
write("The file API isn't supported on this browser yet.");
return;
}
input = document.getElementById('tinymce-uploader');
// var URL = document.my_form.my_field.value;
alert(input.files[0]);
if (!input) {
write("Um, couldn't find the imgfile element.");
} else if (!input.files) {
write("This browser doesn't seem to support the `files`
property of file inputs.");
} else if (!input.files[0]) {
write("Please select a file before clicking 'Load'");
alert( input.files[0]);
} else {
file = input.files[0];
fr = new FileReader();
fr.onload = createFile;
fr.readAsDataURL(file);
// alert(fr.result);
}
function createFile() {
//what should I write here?
ed.insertContent('<a href="'+img.src+'">download
file_name</a>');
}
});
}
}
});