I have this problem using dropzone.js for uploading files with drag&drop.
Lets say i have this form:
<form action=""<?php echo $_SERVER['PHP_SELF'];?>"" enctype=""multipart/form-data"" class=""dropzone"" id=""dropzone1"">
<input type=""text"" name=""somevalue"" id=""somevalue"" value=""somevalue"" />
<div class=""fallback"">
<input type=""file"" name=""file-image"" />
</div>
</form>
The javascript for the dropzone call is :
<script type=""text/javascript"">
$(document).ready(function() {
Dropzone.autoDiscover = false;
var fileList = new Array;
var i =0;
$(""#dropzone1"").dropzone({
init: function() {
var $this = this;
$(""#submit-all-1"").click(function() {
$this.processQueue();
});
var totalFiles = 0,completeFiles = 0;
this.on(""addedfile"", function (file) {
totalFiles += 1;
var numQueued=this.getQueuedFiles().length;
});
this.on(""success"", function(file, serverFileName) {
fileList[i] = {""serverFileName"" : serverFileName, ""fileName"" : file.name,""fileId"" : i };
i++;
});
this.on(""removed file"", function (file) {
totalFiles -= 1;
});
this.on(""complete"", function (file) {
completeFiles += 1;
if (completeFiles === totalFiles) {
// Do something
}
});
},
paramName: 'file-image',
acceptedFiles:'image/*',
autoProcessQueue:false,
addRemoveLinks: true,
parallelUploads: 10
});
/////////////////////////////////
});
</script>
And in php section:
<?php
if (!empty($_FILES)) {
$somevalue=$_POST['somevalue'];
$counter=1;
$image=$_FILES['file-image']['name']);
$picture_in = ""/PicsUrl/"".$somevalues.$counter.$image;
move_uploaded_file($_FILES['file-image']['tmp_name'], $picture_in);
$counter++;
}
?>
I want to do this :
With the $somevalue posted, all the files that i upload simultanously,
to be renamed like that:
$somevalue_1_imagefilename,$somevalue_2_imagefilename,$somevalue_3_imagefilename
etc....
Any help ?
Try changing your PHP script like the below :
<?php
if (!empty($_FILES)) {
$somevalue=$_POST['somevalue'];
$counter=1;
$image=$_FILES['file-image']['name']);
$picture_in = ""/PicsUrl/"".$somevalue.$counter++.$image;
move_uploaded_file($_FILES['file-image']['tmp_name'], $picture_in);
}
?>
Related
I want to add a custom button to the Summernote toolbar that opens up a dialog that has a textbox for a URL and several checkboxes for settings. I then want to use the info from the dialog to scrape web pages and do processing on the content. The ultimate goal is to place the scraped content into the editor starting where the cursor is. I've searched and found some code on creating a custom button, but not any solid examples of implementing a dialog. I went through the summernote.js code to see how the Insert Image dialog works and that left me really confused. The test code I've got so far is in the code block, below. Thanks in advance to anyone who can help get me sorted out.
var showModalDialog = function(){
alert("Not Implemented");
};
var AddWiki = function(context) {
var ui = $.summernote.ui;
var button = ui.button({
contents: '<i class="fa fa-plus"/> Add Wiki',
tooltip: "Set a New Wiki",
class: "btn-primary",
click: function() {
showModalDialog();
}
});
return button.render();
};
$(".tw-summernote-instance textarea").summernote({
airMode: false,
dialogsInBody: false,
toolbar: [["mybutton", ["customButton"]]],
buttons: {
customButton: AddWiki
},
callbacks: {
onInit: function(e) {
var o = e.toolbar[0];
jQuery(o)
.find("button:first")
.addClass("btn-primary");
}
}
});
I found a good, simple example of what I wanted to do. Here's the code:
(function(factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = factory(require('jquery'));
} else {
// Browser globals
factory(window.jQuery);
}
}(function($) {
$.extend($.summernote.plugins, {
'synonym': function(context) {
var self = this;
var ui = $.summernote.ui;
var $editor = context.layoutInfo.editor;
var options = context.options;
context.memo('button.synonym', function() {
return ui.button({
contents: '<i class="fa fa-snowflake-o">',
tooltip: 'Create Synonym',
click: context.createInvokeHandler('synonym.showDialog')
}).render();
});
self.initialize = function() {
var $container = options.dialogsInBody ? $(document.body) : $editor;
var body = '<div class="form-group">' +
'<label>Add Synonyms (comma - , - seperated</label>' +
'<input id="input-synonym" class="form-control" type="text" placeholder="Insert your synonym" />'
'</div>'
var footer = '<button href="#" class="btn btn-primary ext-synonym-btn">OK</button>';
self.$dialog = ui.dialog({
title: 'Create Synonym',
fade: options.dialogsFade,
body: body,
footer: footer
}).render().appendTo($container);
};
// You should remove elements on `initialize`.
self.destroy = function() {
self.$dialog.remove();
self.$dialog = null;
};
self.showDialog = function() {
self
.openDialog()
.then(function(data) {
ui.hideDialog(self.$dialog);
context.invoke('editor.restoreRange');
self.insertToEditor(data);
console.log("dialog returned: ", data)
})
.fail(function() {
context.invoke('editor.restoreRange');
});
};
self.openDialog = function() {
return $.Deferred(function(deferred) {
var $dialogBtn = self.$dialog.find('.ext-synonym-btn');
var $synonymInput = self.$dialog.find('#input-synonym')[0];
ui.onDialogShown(self.$dialog, function() {
context.triggerEvent('dialog.shown');
$dialogBtn
.click(function(event) {
event.preventDefault();
deferred.resolve({
synonym: $synonymInput.value
});
});
});
ui.onDialogHidden(self.$dialog, function() {
$dialogBtn.off('click');
if (deferred.state() === 'pending') {
deferred.reject();
}
});
ui.showDialog(self.$dialog);
});
};
this.insertToEditor = function(data) {
console.log("synonym: " + data.synonym)
var dataArr = data.synonym.split(',');
var restArr = dataArr.slice(1);
var $elem = $('<span>', {
'data-function': "addSynonym",
'data-options': '[' + restArr.join(',').trim() + ']',
'html': $('<span>', {
'text': dataArr[0],
'css': {
backgroundColor: 'yellow'
}
})
});
context.invoke('editor.insertNode', $elem[0]);
};
}
});
}));
I've created a nice little KendoUI grid with drag and drop. It works great... as long as I have the developer tools open. Any idea why this would work with the dev tools open, but doesn't work at all with just using the browser?
Edit to add the code:
my cshtml page:
<div id="DisplayOrderGridContainer">
<div class="validation-error-box" id="errorMessages" style="display:none">
<span>Error!</span>
<ul id="message">
<li>The Record you attempted to edit was modified by another user after you got the original value. The edit operation was canceled.</li>
</ul>
</div>
<div style="padding-bottom: 15px;">
#Html.ActionLink("Back", Model.BackActionName, Model.ControllerName, Model.BackRouteValues, new { id = Model.ControllerName + "_Back", #class = "k-button" })
#if (Model.AllowClearingDisplayOrder)
{
#Html.ActionLink("Clear Order", Model.ClearActionName, Model.ControllerName, Model.BackRouteValues, new { #id = "clear-button", #class = "k-button float-right" })
}
</div>
<div id="KendoGridContainer">
<div id="ChangeDisplayOrderGrid"
class="grid"
data-role="grid"
data-bind="source:data, events:{dataBound:onDataBound,columnHide:OnColumnHide,columnShow:OnColumnShow}"
data-filterable="false"
data-sortable="false"
data-column-menu="true"
data-row-template="rowTemplate"
#*data-toolbar='[{ "template": kendo.template($("#toolbarTemplate").html()) }]'*#
data-columns='[{title:"Short Name", field:"NameField", width: 80, headerAttributes:{id: "#Model.ControllerName" + "_ShortName"}},
{title:"Description", field:"DescriptionField", width:300, headerAttributes:{id: "#Model.ControllerName" + "_Description"}},
{title:"Display Order", field:"Display", width:140, headerAttributes:{id: "#Model.ControllerName" + "_Display"}},
{title:"Value", field:"Value", hidden: true, headerAttributes:{id: "#Model.ControllerName" + "_Value"}}]'>
</div>
<script id="rowTemplate" type="text/x-kendo-tmpl">
<tr class="k-master-row" data-uid="#:uid#">
<td class="text-right">#=NameField#</td>
<td class="text-right">#=DescriptionField#</td>
<td class="text-right">#=Display#</td>
<td class="text-right" style="display:none;">#=Value#</td>
</tr>
</script>
<div id="grid" data-grid-url="#(Url.Action(Model.ActionName, Model.ControllerName))" data-grid-viewdataid="#ViewData.ID()"></div>
</div>
<input type="hidden" id="displayOrderId" />
<input type="hidden" id="Id" />
my js page:
$(document).ready(function () {
UnsavedWarningsModule.ClearUnsavedChanges();
var newData = new kendo.data.DataSource({
transport: {
read: {
url: $('#grid').attr('data-grid-url'),
dataType: "json"
}
},
schema: {
model: {
id: "Id"
}
}
})
var viewModel = new kendo.observable({
data: newData,
onDataBound: function (e) {
pfsKendoGridEvents.SetSelectedRow_MVVMGrid("KendoGridContainer", e.sender, $('#grid').attr('data-grid-viewdataId'))
},
OnColumnHide: function (e) {
pfsKendoGridEvents.OnHideShowColumns(e);
},
OnColumnShow: function (e) {
pfsKendoGridEvents.OnHideShowColumns(e);
}
});
kendo.bind($("#DisplayOrderGridContainer"), viewModel);
kendo.addDragAndDropToGrid = function (gridId, rowClass, viewModel) {
if (!gridId) { throw "Parameter [gridId] is not set."; }
if (!rowClass) { throw "Parameter [rowClass] is not set."; }
$(rowClass).kendoDraggable({
hint: function (element) {
var shortName = element[0].cells[0].firstChild.data;
var desc = element[0].cells[1].firstChild.data;
var dispOrder = element[0].cells[2].firstChild.data;
element[0].innerHTML = "<td class=\"text-right dragOver\" style=\"width:95px\">" + shortName + "</td><td class=\"text-right dragOver\" style=\"width:382px\">" + desc + "</td><td class=\"text-right dragOver\" style=\"width:173px\">" + dispOrder + "</td>";
return element;
},
axis: "y",
container: $(gridId)
});
$(gridId).kendoDropTargetArea({
filter: rowClass,
drop: function (e) {
var srcUid = e.draggable.element.data("uid");
var tgtUid = e.dropTarget.data("uid");
var ds = $(gridId).data("kendoGrid").dataSource;
var srcItem = ds.getByUid(srcUid);
var tgtItem = ds.getByUid(tgtUid);
var dstIdx = ds.indexOf(tgtItem);
ds.remove(srcItem);
ds.insert(dstIdx, srcItem);
e.draggable.destroy();
UnsavedWarningsModule.SetUnsavedChanges();
kendo.addDragAndDropToGrid(gridId, rowClass, viewModel);
},
dragenter: function (e) {
e.draggable.hint.css("opacity", 0.3);
},
dragleave: function (e) {
e.draggable.hint.css("opacity", 1);
var srcUid = e.draggable.element.data("uid");
var tgtUid = e.dropTarget.data("uid");
var ds = $(gridId).data("kendoGrid").dataSource;
var srcItem = ds.getByUid(srcUid);
var srcDispOrd = srcItem.Display;
var tgtItem = ds.getByUid(tgtUid);
var tgtDispOrd = tgtItem.Display;
var dstIdx = ds.indexOf(tgtItem);
//--update display orders after dropping
ds._data.forEach(function (data) {
//if dragging it to a spot with higher dispOrder
if (tgtDispOrd > srcDispOrd) {
if (data.Display <= tgtDispOrd && data.Display > srcDispOrd) {
data.Display -= 1;
}
}
//if dragging it to a spot with lower dispOrder
if (srcDispOrd > tgtDispOrd) {
if (data.Display >= tgtDispOrd && data.Display < srcDispOrd) {
data.Display += 1;
}
}
});
srcItem.Display = tgtDispOrd;
//--end
ds.remove(srcItem);
ds.insert(dstIdx, srcItem);
}
});
};
var dataService = (function () {
"use strict";
var self = {};
self.getAddresses = function () {
var data = new kendo.data.ObservableArray([newData]);
// Manual create a promise, so this function mimicks an Ajax call.
var dfd = new $.Deferred();
dfd.resolve(data);
return dfd.promise();
};
return self;
})(kendo);
var controller = (function (dataService, viewModel) {
"use strict";
var _dataService = dataService;
var _vm = viewModel;
var self = {};
self.handleAddressesRefresh = function (data) {
_vm.set("addresses", new kendo.data.DataSource({ data: data }));
kendo.bind($("#KendoGridContainer"), _vm);
kendo.addDragAndDropToGrid("#ChangeDisplayOrderGrid", ".k-master-row", _vm);
};
self.show = function () {
$.when(_dataService.getAddresses())
.then(self.handleAddressesRefresh);
};
return self;
})(dataService, viewModel);
controller.show();});
I think it's something to do with the timing of the loading of the page, possibly with the promise I'm using?
Thanks!
How read and write html or php file using ace editor ( alloyoui ), in the example i just get value to edit not from file and i have done to see the documentation but not get how read and write code from file.
example
YUI().use(
'aui-ace-editor',
function(Y) {
var editor = new Y.AceEditor(
{
boundingBox: '#myEditor',
height: '200',
mode: 'javascript',
value: 'alert("Write something here...");',
width: '700'
}
).render();
var mode = Y.one('#mode');
if (mode) {
var contents = {
javascript: 'alert("Write something here...");',
json: '{"value": "Write something here..."}',
php: '<?php echo "Write something here..."; ?>',
xml: '<value attr="something">Write something here...</value>'
};
var currentMode = 'javascript';
var updateValue = function() {
editor.set('value', contents[currentMode]);
};
mode.on(
'change',
function(event) {
currentMode = this.val();
editor.set('mode', currentMode);
updateValue();
}
);
}
}
);
how call the file code? or this can be done only change the value: 'alert("Write something here...");'whit file path/url?
thanks
You cannot write to or read system files with JavaScript. However, you can kind of write to files by reading the contents of uploaded files and loading them into the AceEditor. Use an <input type="file" /> to allow the user to upload the file. Once the file is uploaded, set the AceEditor's value to be the file's contents.
AUI().use('aui-ace-editor', function(A) {
var aceEditor;
var fileInput = A.one('#fileInput');
fileInput.on('change', function(event) {
var file = fileInput.getDOMNode().files[0];
if (file) {
// Other types may also be appropriate here:
if (file.type.startsWith('text/') || file.type.startsWith('application/')) {
var reader = new FileReader();
reader.onload = function (onloadEvent) {
if (!aceEditor) {
aceEditor = new A.AceEditor({
/* ...your AceEditor config... */
mode: 'text',
render: true
});
}
aceEditor.set('value', onloadEvent.target.result);
}
reader.onerror = function (onerrorEvent) {
alert('File could not be read. Aborting.')
}
reader.readAsText(file, "UTF-8");
}
else {
alert('File does not contain text. Aborting.');
}
}
});
});
You can also attempt to guess the mode that the editor should use from the file's mime type:
aceEditor.set('mode', file.type.replace(/^(text|application)\/(x-)?/, ''));
To download the edited file, you can use a data URI:
var downloadFileButton = Y.one('#downloadFileButton');
downloadFileButton.on('click', function(clickEvent) {
var downloadFileLink = Y.Node.create('<a href="data:' +
fileType + ';charset=utf-8,' +
encodeURIComponent(aceEditor.get('value')) +
'" download="' + fileName + '" style="display: none;" />');
var bodyElement = Y.one('body');
bodyElement.appendChild(downloadFileLink);
downloadFileLink.getDOMNode().click();
bodyElement.removeChild(downloadFileLink);
});
Here's a runnable example with all of the above features/code:
YUI().use('aui-ace-editor', function(Y) {
var aceEditor;
var fileName;
var fileType;
var fileInput = Y.one('#fileInput');
fileInput.on('change', function(event) {
var file = fileInput.getDOMNode().files[0];
if (file) {
fileType = file.type;
// Other types may also be appropriate here:
if (fileType.startsWith('text/') || fileType.startsWith('application/')) {
fileName = file.name;
var reader = new FileReader();
reader.onload = function (onloadEvent) {
if (!aceEditor) {
aceEditor = new Y.AceEditor({
boundingBox: '#aceEditor',
mode: 'text',
value: 'Upload a file to begin editing.',
height: '200',
width: '700',
render: true
});
var downloadFileButton = Y.one('#downloadFileButton');
downloadFileButton.setStyle('display', null);
downloadFileButton.on('click', function(clickEvent) {
var downloadFileLink = Y.Node.create('<a href="data:' +
fileType + ';charset=utf-8,' +
encodeURIComponent(aceEditor.get('value')) +
'" download="' + fileName + '" style="display: none;" />');
var bodyElement = Y.one('body');
bodyElement.appendChild(downloadFileLink);
downloadFileLink.getDOMNode().click();
bodyElement.removeChild(downloadFileLink);
});
}
aceEditor.set('value', onloadEvent.target.result);
aceEditor.set('mode', fileType.replace(/^(text|application)\/(x-)?/, ''));
}
reader.onerror = function (onerrorEvent) {
alert('File could not be read. Aborting.')
}
reader.readAsText(file, "UTF-8");
}
else {
alert('File does not contain text. Aborting.');
}
}
});
});
<script src="https://cdn.rawgit.com/stiemannkj1/701826667a70997013605edcd37e92a6/raw/469fe1ae297e72a5a80eb9015003b7b04eac735e/alloy-ui-3.0.1_aui_aui-min.js"></script>
<link href="https://cdn.rawgit.com/stiemannkj1/90be22de7f48c729b443af14796d91d3/raw/a9f35ceedfac7fc0559b121bed105eaf80f10bf2/aui-css_css_bootstrap.min.css" rel="stylesheet"></link>
<div class="yui3-skin-sam">
<input type="file" id="fileInput">
<div id="aceEditor"></div>
<button id="downloadFileButton" style="display: none;">Download File</button>
</div>
Is it possible to combine Google's incredible reCAPTCHA and Matias Meno's incredible dropzone.js, to prevent attacks and deter spam bots?
Using wordpress.
This is what I came up with following a few tutorials:
SO answer
codeforgeek
And some others I dont remember
// Dropzone.autoDiscover = false; //I use Autodiscover
Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element
// The configuration we've talked about above
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
previewsContainer: '.fileupload',
// The setting up of the dropzone
init: function() {
var myDropzone = this;
// First change the button to actually tell Dropzone to process the queue.
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
// myDropzone.processQueue();
var valid = true;
$('[data-required]').each(function(i,ele){
if(ele.value == ''){
$(this).parent().parent().addClass('alert');
valid = false;
}
});
if (!valid){
e.preventDefault();
scrollTop();
return false;
}
// Get the recaptcha input
var cap_input = grecaptcha.getResponse();
$.ajax({
url: homeUrl+'/wp-admin/admin-ajax.php',
type: "POST",
dataType: "JSON",
data: {
"action": "verifyReCaptcha",
"g-recaptcha-response": cap_input
},
success: function(response){
console.log(response);
if(response == 'Good captcha'){
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
}
else {
// Upload anyway without files
if (wantToUpload == 'unknown') {
$('#noFiles').modal();
e.preventDefault();
return false;
}
else if (wantToUpload == false) {
myDropzone.uploadFiles([ ]);
}
else {
myDropzone.uploadFiles([ ]);
}
}
}
else{
console.log('Spammer go away');
$('.g-recaptcha').addClass('alert');
}
}
});
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
console.log('sending');
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
console.log('success');
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
console.log('error');
});
}
}
And some html/php
<form name="" action="<?=get_permalink();?>" method="post" id="my-awesome-dropzone" class="dropzone" enctype="multipart/form-data">
<label class="label" for="text-435">
<?=__('Name*','gt_domain');?>
</label>
<input type="text" name="client-name" value="" size="40" class="input__field--manami" id="text-435" data-required="true">
<!-- Lots of input fields -->
<div class="col-md-8 col-xs-12 fileupload dropzone-previews dz-message">
<h2 class="text-center" id="fileuploadtext">
<?=__('Click or drag and drop your file here <br>(Max 60mb)','gt_domain');?>
</h2>
</div>
<div class="g-recaptcha" data-sitekey="MY_PUBLIC_KEY"></div>
<input class="dangerzone-submit" type="submit" value="<?=__('Request quote','gt_domain');?>" name="dangerzone-submit">
</form>
And for ajax validation before submitting the form:
function verifyReCaptcha(){
$email;
$comment;
$captcha = false;
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo json_encode('Please check the the captcha form.');
exit;
}
$response=json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=MY_SUPER_SECRET_GOOGLE_RECAPTCHA_KEY&response=".$captcha."&remoteip=".$_SERVER['REMOTE_ADDR']), true);
if($response['success'] == false){
echo json_encode('You are spammer ! Get the #$%K out');
}
else{
echo json_encode('Good captcha');
}
exit;
}
add_action( 'wp_ajax_nopriv_verifyReCaptcha', 'verifyReCaptcha' );
add_action( 'wp_ajax_verifyReCaptcha', 'verifyReCaptcha' );
And finnaly recieve form inputs and images:
<?php
if (isset($_POST['dangerzone-submit'])) {
// print_r($_POST);
$client = $_POST['client-name'];
$email = $_POST['email'];
$company = $_POST['company'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if ($_FILES) {
foreach ($_FILES as $file => $array) {
// print_r($array);
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK && $_FILES[$file]['error'][0] !== 0) {
echo "upload error : \n";
print_r($_FILES[$file]['error']);
print_r($_FILES);
die();
}
$uploads_dir = ABSPATH . 'wp-content/uploads/dropzone/';
$external_link = get_home_url().'/wp-content/uploads/dropzone/';
foreach ($array['name'] as $key => $val) {
print_r($key);
$name = $array['name'][$key];
$tmp_name = $array['tmp_name'][$key];
$newfilename = wp_unique_filename( $uploads_dir, $name );
$movefile = move_uploaded_file($tmp_name, $uploads_dir.$newfilename);
$uploaded_files[] = $external_link.$newfilename;
}
}
}
sendMail( //My func for sending mail
$client,
$email,
$company,
$phone,
$comments,
$uploaded_files
);
}
?>
Hi I was wondering if there was a way to preview images before I upload them using angularjs? I am using the this library. https://github.com/danialfarid/angular-file-upload
Thanks. Here is my code:
template.html
<div ng-controller="picUploadCtr">
<form>
<input type="text" ng-model="myModelObj">
<input type="file" ng-file-select="onFileSelect($files)" >
<input type="file" ng-file-select="onFileSelect($files)" multiple>
</form>
</div>
controller.js
.controller('picUploadCtr', function($scope, $http,$location, userSettingsService) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$http.uploadFile({
url: 'server/upload/url', //upload.php script, node.js route, or servlet uplaod url)
data: {myObj: $scope.myModelObj},
file: $file
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
OdeToCode posted great service for this stuff. So with this simple directive you can easily preview and even see the progress bar:
.directive("ngFileSelect",function(){
return {
link: function($scope,el){
el.bind("change", function(e){
$scope.file = (e.srcElement || e.target).files[0];
$scope.getFile();
});
}
}
It is working in all modern browsers!
Example: http://plnkr.co/edit/y5n16v?p=preview
JavaScript
$scope.setFile = function(element) {
$scope.currentFile = element.files[0];
var reader = new FileReader();
reader.onload = function(event) {
$scope.image_source = event.target.result
$scope.$apply()
}
// when the file is read it triggers the onload event above.
reader.readAsDataURL(element.files[0]);
}
Html
<img ng-src="{{image_source}}">
<input type="file" id="trigger" class="ng-hide" onchange="angular.element(this).scope().setFile(this)" accept="image/*">
This worked for me.
See the Image Upload Widget from the Jasney extension of Bootstrap v3
// start Picture Preview
$scope.imageUpload = function (event) {
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
var reader = new FileReader();
reader.onload = $scope.imageIsLoaded;
reader.readAsDataURL(file);
}
}
$scope.imageIsLoaded = function (e) {
$scope.$apply(function () {
$scope.img = e.target.result;
});
}
<input type='file' ng-model-instant onchange="angular.element(this).scope().imageUpload(event)" />
<img class="thumb" ng-src="{{img}}" />