this is my html
<input type="text" name="message" ng-model="senderMessage">
<button type="submit" ng-click="sendSenderMessage(1,5,senderMessage)">
click me
</button>
my js controller function
$scope.sendSenderMessage = function (bsid, srid, message) {
$scope.senderMessage = message;
$http.post(url + 'c_chat/sendSenderMessageJson', {
bsid: bsid,
srid: srid,
message: $scope.senderMessage
})
.success(function (data) {
console.log(data);
$scope.chatForm();
$scope.startChat(srid);
});
}
where
$scope.chatForm = function () {
$scope.senderMessage = "";
}
MY problem is that i can not reset $scope.senderMessage blank
you should provide .error(function(data)) to post request because if error occurs then $scope.chatForm will not called and $scope.senderMessage will remain same.
or you should do like
var tempMessage = angular.copy(message);
$scope.senderMessage = "";
$http.post(url + 'c_chat/sendSenderMessageJson', {
'bsid' : bsid ,
'srid' : srid ,
'message' : tempMessage
})
$scope.sendSenderMessage = function (bsid, srid, message) {
$scope.senderMessage = message;
$http.post(url + 'c_chat/sendSenderMessageJson', {
bsid: bsid,
srid: srid,
message: $scope.senderMessage
})
.success(function (data) {
console.log(data);
$scope.chatForm();
$scope.startChat(srid);
});
where $scope.chatForm = function() {
$scope.senderMessage = "";
$timeout(angular.noop); //use
//try let me know again u are getting same problem.
}
angular.noop is an empty function that can be used as a placeholder when you need to pass some function as a param.
For more details regarding angular.noop
My problem started when I tried to add a library SignalR in my AngularJs project. I do not know why but the data flow has stopped working properly, I mean that when I try to insert an object into an array I do not see it, but when I try to add another one I see first object, and when I try to add a third object I see only the second.
edit : all code in the angular controller.
app.controller('HomeCtrl', ['$scope', 'HttpSrv', '$state', function ($scope, HttpSrv, $state) {
$scope.messages = [];
activate();
function activate() {
if (HttpSrv.CheckToken()) {
loadPage();
}
};
$scope.$on("$destroy", function () {
con.stop();
});
function connectToChat() {
HttpSrv.http('GET', 'home/GetChatToken').then(function (res) {
localStorage.setItem('ChatToken', res.Result);
con.start({ jsonp: true }, function () { console.log('Start'); });
});
}
var con = $.hubConnection("http://localhost:4704/");
var hub = con.createHubProxy('ChatHub');
hub.on('fail', function (res) {
console.error(res);
});
hub.on('addMessage', addMessage);
$scope.trySend = function () {
hub.invoke('SendMessage', localStorage.getItem('ChatToken'), document.getElementById('messageBox').value);
};
function addMessage(name, message, elementId) {
var tempMessage = '<li id="' + elementId + '" class="right clearfix"><div class="chat-body clearfix">'
tempMessage += '<div class="header"><strong class="pull-left primary-font">' + name + ': </strong> <br />'
tempMessage += '</div><p>' + message + '</p></div></li>'
document.getElementById('chatBody').innerHTML += tempMessage;
document.getElementById('messageBox').value = '';
document.getElementById(elementId).scrollIntoView();
document.getElementById('chatBody').focus();
}
function loadPage() {
HttpSrv.http('GET', 'home/get').then(function (res) {
//console.log(res);
if (res.Status == 200 && res.Succeeded) {
connectToChat();
for (var i = 0; i < res.ListResult.length; i++) {
res.ListResult[i].CreateDate = res.ListResult[i].CreateDate.replace('T', ' ').slice(0, 19);
}
$scope.newsList = res.ListResult;
}
});
};}]);
(i use document.getElementById because of the problem)
First, you shouldn't be building markup in your code. Simply add the message to the list and use ng-repeat in your markup.
However, you also must make sure you use $scope.$apply() or $scope.$digest() when you are processing messages from signalR.
function addMessage(name, message, elementId) {
$scope.$apply(function(){
$scope.messages.push(message);
});
}
Am using the following module https://github.com/danialfarid/ng-file-upload and it has well documented except for aborting the upload process. During uploading the files, The code for cancel the upload is not working fine.
Am getting error that says 'abort is not a function' and I do not know how to apply the abort() function to cancel the upload process.
I dont know what i missed here, Could anyone give me some idea on why? or any suggestion please.
My html
<body ng-app="fileUpload" ng-controller="MyCtrl">
<h4>Upload on file select</h4>
<button ngf-select="uploadFiles($files)" multiple
accept="image/*,audio/*,video/*">Select Files</button>
<span class="progress" ng-show="progress >= 0">
<div style="width:{{progress}}%" ng-bind="progress + '%'"></div>
</span>
{{errorMsg}}
<button ng-click="cancelUpload()">Cancel</button>
</body>
JS(Angular)
var app = angular.module('fileUpload', ['ngFileUpload']);
app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', function ($scope, Upload, $timeout) {
var upload = "";
$scope.uploadFiles = function (files) {
$scope.files = files;
if (files && files.length) {
upload = Upload.upload({
url: 'https://angular-file-upload-cors-srv.appspot.com/upload',
data: {
files: files
},
resumeSize: function() {return promise;}
}).then(function (response) {
$timeout(function () {
$scope.result = response.data;
});
}, function (response) {
if (response.status > 0) {
$scope.errorMsg = response.status + ': ' + response.data;
}
}, function (evt) {
$scope.progress =
Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
};
$scope.cancelUpload = function(files){ // here is my cancel program
console.log("Cancelling");
upload.abort(); // this 'abort()' is not working as mentined
}
I'm trying to upload a file in IE7 and IE8 browser using FileAPI library, but unfortunately it is not working. It is working in all the other browser but not in IE7, IE8 and it is my business requirement to make it work in IE7, IE8 too.
Here is my js code
jQuery(function ($){
$(document)
.on('click', '.imageLabel', function (evt){
imageUploadId = $(this).attr("id").split("_")[1];
previewImage = document.getElementById('previewHolderDiv_' + imageUploadId);
$("#imageError_" + imageUploadId).html("");
errorMessageUl = document.getElementById('imageError_' + imageUploadId);
removeImageIcon = document.getElementById('removeImage_' + imageUploadId);
})
var form = document.forms.vehicleDocumentForm;
var input = form.vehicleImage;
var uploadOpts = {
url: '/save-vehicle-document',
data: {},
name: 'vehicleImage',
activeClassName: 'upload_active'
};
var _onSelectFile = function (evt/**Event*/){
var file = FileAPI.getFiles(evt)[0];
if( file ){
_uploadFile(file, imageUploadId);
}
};
var _uploadFile = function (file){
uploadOpts.data = {"imageId" : imageUploadId};
var opts = FileAPI.extend(uploadOpts, {
files: {},
upload: function (){
form.className += ' '+uploadOpts.activeClassName;
},
complete: function (err, xhr){
//enableSellYourButtons();
form.className = (' '+form.className+' ').replace(' '+uploadOpts.activeClassName+' ', ' ');
var response = JSON.parse(xhr.responseText);
if( response.result == "fail"){
previewImage.html = "";
$("#imageError_" + imageUploadId).html("<li>" + response.message + "</li>");
} else {
$("#imageError_" + imageUploadId).html("");
$("#vehicleImageName_" + imageUploadId).attr("value", response.message);
}
}
});
opts.files[opts.name] = file;
FileAPI.upload(opts);
};
FileAPI.event.on(input, "change", _onSelectFile);
}); // ready
I'm getting an error
SCRIPT445: Object doesn't support this action
File: FileAPI.min.js, Line: 2, Column: 11608
My FileAPI version is 2.0.11
Any help would be greatly appreciated.
Thank you.
According to caniuse, the FileApi is not compatible with IE7/8.
I would like to know if it is possible to download files that have been uploaded with Dropzone. For example add to the file that are shown in the dropzone a link or a button to download.
The code for upload and to show the files already uploaded:
index.php
<html>
<head>
<link href="css/dropzone.css" type="text/css" rel="stylesheet" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="dropzone.min.js"></script>
<script>
Dropzone.options.myDropzone = {
init: function() {
thisDropzone = this;
$.get('upload.php', function(data) {
$.each(data, function(key,value){
var mockFile = { name: value.name, size: value.size };
thisDropzone.emit("addedfile", mockFile);
thisDropzone.emit("thumbnail", mockFile, "uploads/"+value.name);
});
});
thisDropzone.on("addedfile", function(file) {
var removeButton = Dropzone.createElement("<button>Remove</button>");
var _this = this;
removeButton.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
_this.removeFile(file);
});
file.previewElement.appendChild(removeButton);
});
thisDropzone.on("removedfile", function(file) {
if (!file.serverId) { return; }
$.post("delete-file.php?id=" + file.serverId);
});
}
};
</script>
</head>
<body>
<form action="upload.php" class="dropzone" id="my-dropzone"></form>
</body>
</html>
upload.php
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder = 'uploads';
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;
$targetFile = $targetPath. $_FILES['file']['name'];
move_uploaded_file($tempFile,$targetFile);
} else {
$result = array();
$files = scandir($storeFolder);
if ( false!==$files ) {
foreach ( $files as $file ) {
if ( '.'!=$file && '..'!=$file) {
$obj['name'] = $file;
$obj['size'] = filesize($storeFolder.$ds.$file);
$result[] = $obj;
}
}
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
?>
any help will be much appreciated
Yes I found it possible by altering the dropzone.js file, not ideal for updates but only way I found that worked for me.
Add these 6 lines of code to the addedfile: function around line 539 note Ive marked the code that exists already
// the following line already exists
if (this.options.addRemoveLinks) {
/* NEW PART */
file._openLink = Dropzone.createElement("<a class=\"dz-open\" href=\"javascript:undefined;\">Open File</a>");
file._openLink.addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
window.open("http://www.mywebsite.com/uploadsdirectory/"+file.name);
});
/* END OF NEW PART */
// the following lines already exist
file._removeLink = Dropzone.createElement("<a class=\"dz-remove\" href=\"javascript:undefined;\">" + this.options.dictRemoveFile + "</a>");
file._removeLink.addEventListener("click", function(e) {
Then you'll need to edit the CSS with a class 'dz-open', to style the button.
myDropzone.on("success", function(file) {
var a = document.createElement('a');
a.setAttribute('href',"/uploads/" + file.fullname);
a.innerHTML = "<br>download";
file.previewTemplate.appendChild(a);
});
This can be accomplished using the the example below. You will still need to tweak it to your needs.
I want to display additional information after a file uploaded.
To use the information sent back from the server, use the success
event, like this:
Dropzone.options.myDropzone = {
init: function() {
this.on("success", function(file, responseText) {
// Handle the responseText here. For example,
// add the text to the preview element:
file.previewTemplate.appendChild(document.createTextNode(responseText));
});
}
};
Use this in init function after ajax call. I had the same issue. Solved using this.
$('.dz-details').each(function(index, element) {
(function(index) {
$(element).attr('id', "filename_" + index);
var selectFile = document.querySelector("#filename_" + index);
selectFile.addEventListener("click", function () {
window.open("http://localhost:8080/<<contextpath>>/pathtofile/" + $('#filename_' + index + '> div > span').text());
});
}(index));
});
you can also add a empty link to your images and when your upload is ready you can fetch the image-src and set it to your link ;)
<a href="#">
<img src="" data-dz-thumbnail/>
</a>
$("img.data-dz-thumbnail").each(function() {
$(this).closest("a").attr("href", $(this).attr("src"));
$(this).closest("a").attr("target", "_blank");
});
My code is something like this.
success: function(file, rawResponse){
file.previewElement.onclick = function() {
alert(1);//do download
}
},
code is..
$('.dz-details').each(function(index, element) {
(function(index) {
$(element).attr("id", "filename_" + index);
$("#filename_" + index).on("click", function(){
window.open("URL/path/folder/" + $('#filename_' + index + '> div > span').text());
});
}(index));
});
Yes. I found a way by adding a custom preview template (adding a download button there and setting a data-file-id attribute). Then when defining the dropzone on the document ready, I searched for the last generated button element and modified the "data-file-id" attribute to save the file id.
I did the same on the 'success' event of dropzone.
After this I listened to the on click event of the download button and looked for the data-file-id attribute.
var oakDropzone = new Dropzone("#oakDropzone", {
url: "/trabajo/uploadFile",
init: function () {
var trabajoId = $("#trabajoId").val();
var getArchivosUrl = "/trabajo/getArchivosByTrabajo?trabajoId=" + trabajoId;
$("#fileLoader").show();
$.get(getArchivosUrl)
.done(function (response) {
for (var i = 0; i < response.data.length; i++) {
var file = response.data[i];
var fileData = { id: file.Id, name: file.Nombre, size: file.TamaƱo, metadata: file.Metadata };
fileData.accepted = true;
oakDropzone.files.push(fileData);
oakDropzone.emit('addedfile', fileData);
oakDropzone.emit('thumbnail', fileData, 'data:' + response.data[i].Extension + ';base64,' + response.data[i].Preview);
oakDropzone.emit('complete', fileData);
$(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', fileData.id);
}
$("#fileLoader").hide();
$('#oakDropzone #template .dz-details .actionButtons .downloadFile').on('click', function (event) {
event.preventDefault();
var archivoId = $(this).data('file-id');
var downloadUrl = "http://localhost:11154/trabajo/downloadFile?fileId=" + archivoId;
window.open(downloadUrl, 'blank');
});
}).catch(function (response) {
displayErrorToaster(response);
});
this.on("sending", function (file, xhr, formData) {
formData.append("Id", trabajoId);
formData.append("File", file);
});
this.on("success", function (file, response) {
file.id = response.data;
$(oakDropzone.element[oakDropzone.element.length - 1]).attr('data-file-id', file.id);
displaySuccessToaster(response);
});
this.on("removedfile", function (file) {
var deleteUrl = "/trabajo/RemoveFile?fileId=" + file.id;
$.post(deleteUrl)
.done(function (response) {
displaySuccessToaster(response);
}).catch(function (response) {
displayErrorToaster(response);
});
});
},
dictRemoveFileConfirmation: 'Realmente desea quitar el archivo seleccionado?',
dictDefaultMessage: '',
clickable: "#btnUploadFile",
previewTemplate: document.querySelector('#previews').innerHTML,
addRemoveLinks: false
});
This looks like the following image:
Sample Image
Hope this helps you!.
Mine looks like this, this will add "download" anchor after "remove" and it will directly download the file. ("self" is just dropzone selector)
var a = document.createElement('a');
a.setAttribute('href',existing_file.url);
a.setAttribute('rel',"nofollow");
a.setAttribute('target',"_blank");
a.setAttribute('download',existing_file.name);
a.innerHTML = "<br>download";
self.find(".dz-remove").after(a);