Using Angular 1.x I want to provide a drag and drop box for uploading images. When the images have been dropped I want to show a preview in the front end.
This is my code:
dropbox.addEventListener("drop", function(evt) {
evt.stopPropagation();
evt.preventDefault();
$scope.$apply(function(){
$scope.dropText = 'Drop files here...';
$scope.dropClass = '';
});
var files = evt.dataTransfer.files;
if (files.length > 0) {
$scope.listing.listing_images = [];
$scope.imagepreview = [];
for (var i = 0; i < files.length; i++) {
// push the image to be uploaded
$scope.listing.listing_images.push(files[i]);
// push the image to be rendered
var reader = new FileReader();
reader.onload = function (e) {
$scope.imagepreview[i] = e.target.result;
}
reader.readAsDataURL(files[i]);
}
console.log($scope.imagepreview);
console.log($scope.imagepreview.length);
}
}, false);
If I drop say 3 images into the dropbox area and I console.log $scope.imagepreview I can see that the image is stored - so far so good!
[]
0: "data:image/jpeg;base64,/9j/4fzyRXhpZgAATU0AKgAAAAg"
1: "data:image/jpeg;base64,/9j/4f8ERXhpZgAATU0AKgAAAAg"
2: "data:image/jpeg;base64,/9j/4f+eRXhpZgAATU0AKgAAAAg"
length: 3
__proto__: Array(0)
Then on the very next line:
$scope.imagepreview.length 0
This makes no sense and looks like a bug to me, how can Scope object have data but also have a length of 0?
The problem is that in my template when I try to ng-repeat on the $scope.previewimages the object is empty so no images are rendered. Any ideas?
The code is missing an $apply block for the reader load event:
for (var i = 0; i < files.length; i++) {
// push the image to be uploaded
$scope.listing.listing_images.push(files[i]);
// push the image to be rendered
var reader = new FileReader();
reader.onload = function (e) {
//IMPORTANT
$scope.$apply(function() {
$scope.imagepreview[i] = e.target.result;
});
}
reader.readAsDataURL(files[i]);
}
When the FileReader load event handler modifies $scope, the AngularJS frame needs to digest the changes and update the DOM.
For more information, see
AngularJS Developer Guide - Integration with the browser event loop
Related
How to apply delay in JSZip API ? I want to zip multiple file. but I want to add some delay between transferring the files from webserver. How to add delay in below code?
This is for browser and deploying binaries inside the device.
$scope.download = function () {
var urls = ["/FILES/AlertLog.txt",
"/FILES/AuditLog.txt",
"/FILES/TotLog.txt",
"/FILES/Historian.csv",
"/FILES/History2.csv",
"/FILES/Factory.cfg",
"/FILES/SLog.txt",
"/FILES/se.dump",
"/FILES/AssertLog.txt",
"/FILES/History2.csv",
"/FILES/History3.csv",
"/FILES/History4.csv"
];
compress_files(urls);
}
function compress_files(urls) {
var zip = new JSZip();
var deferreds = [];
for (var i = 0; i < urls.length; i++) {
$timeout(function(){ deferreds.push(addToZip(zip, urls[i], i));
},200);// issue to deferreds variable =>undefined
$.when.apply(window, deferreds).done(generateZip);
}
function addToZip(zip, url, i) {
var deferred = $.Deferred();
JSZipUtils.getBinaryContent(url, function (err, data) {
if(err) {
deferred.resolve(zip);
}
else {
var arr=url.split("/");
zip.file(arr[2], data, { binary: true });
deferred.resolve(zip);
}
});
return deferred;
}
add some delay of milliseconds between transferring the files from the webserver.
I am trying to download the individual file by giving some delay. It fixed my problem
function downloadAll(files){
if(files.length == 0) return;
file = files.pop();
var theAnchor = $('<a />')
.attr('href', file[1])
.attr('download',file[0])
// Firefox does not fires click if the link is outside
// the DOM
.appendTo('body');
theAnchor[0].click();
theAnchor.remove();
downloadAll(files); }
function downloadAll(files){
if(files.length == 0) return;
file = files.pop();
var theAnchor = $('<a />')
.attr('href', file[1])
.attr('download',file[0])
// Firefox does not fires click if the link is outside
// the DOM
.appendTo('body');
theAnchor[0].click();
theAnchor.remove();
downloadAll(files);
}
$('a.download-csv').on('click', function(){
downloadAll([
['file1.csv', 'data:text/csv;charset=utf8,'+
encodeURIComponent('my,csv,file\and,so,on')],
['file2.txt', 'data:text/plain;charset=utf8,'+
encodeURIComponent('this script can do what I need.')],
['file3.js', 'data:text/javascriptcharset=utf8,'+
encodeURIComponent('alert(\'You can donate me your house if you like this script :-) \')')]
]);
});
Problem stated as subject.
Looking at references here and here, I have following code, but it does not work.
My current code:
if (window.navigator.userAgent.toLowerCase().indexOf('crios') > -1) {
var byteCharacters = atob(this.state.base64EncodedPDF);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], { type: "application/octet-stream" });
var reader = new FileReader();
reader.onload = function () { reader.result; };
reader.readAsDataURL(blob);
return;
What is the problem here?
EDIT
If you wonder what was the error, there was no error. Nothing just happens when I clicked on the download link. Desktop browsers work fine (of course in other IF conditions).
I am new in firebase and angularjs and i am having difficulties in getting download url from firebase storage and store them in firebase realtime database.
I was able to upload multiple files to firebase storage. the problem is when i store the download url into firebase realtime database, all database url value are same.It should different based each files downloadURL.
Here my script:
$scope.submitPhotos = function(file){
console.log(file);
var updateAlbum = [];
for (var i = 0; i < file.length; i++) {
var storageRef=firebase.storage().ref(albumtitle).child(file[i].name);
var task=storageRef.put(file[i]);
task.on('state_changed', function progress(snapshot){
var percentage=( snapshot.bytesTransferred / snapshot.totalBytes )*100;
if (percentage==100){
storageRef.getDownloadURL().then(function(url) {
var galleryRef = firebase.database().ref('gallery/'+albumkey);
var postkey = firebase.database().ref('gallery/'+albumkey).push().key;
updateAlbum={img:url};
firebase.database().ref('gallery/'+ albumkey+'/'+postkey).update(updateAlbum);
});
};
})
};
};
As you can see i was able store the url into database but all of the urls are same. What i need is every key store each different links from storage.
Any helps appreciated. Thanks
function uploadImg(file,i) {
return new Promise((resolve,reject)=>{
var storageRef=firebase.storage().ref("store-images/"+file[i].file.name);
task = storageRef.put(file[i].file);
task.on('state_changed', function progress(snapshot){
var percentage=( snapshot.bytesTransferred / snapshot.totalBytes )*100;
console.log(percentage);
// use the percentage as you wish, to show progress of an upload for example
}, // use the function below for error handling
function (error) {
console.log(error);
},
function complete () //This function executes after a successful upload
{
task.snapshot.ref.getDownloadURL().then(function(downloadURL) {
resolve(downloadURL)
});
});
})
}
async function putImage(file) {
for (var i = 0; i < file.length; i++) {
var dd = await uploadImg(file,i);
firebase.database().ref().child('gallery').push(dd);
}
}
Try using the code below:
$scope.submitPhotos = function(file){
console.log(file);
var updateAlbum = [];
for (var i = 0; i < file.length; i++) {
var storageRef=firebase.storage().ref(albumtitle).child(file[i].name);
var task=storageRef.put(file[i]);
task.on('state_changed', function progress(snapshot)
{
var percentage=( snapshot.bytesTransferred / snapshot.totalBytes )*100;
// use the percentage as you wish, to show progress of an upload for example
}, // use the function below for error handling
function (error) {
switch (error.code) {
case 'storage/unauthorized':
// User doesn't have permission to access the object
break;
case 'storage/canceled':
// User canceled the upload
break;
case 'storage/unknown':
// Unknown error occurred, inspect error.serverResponse
break;
}
}, function complete () //This function executes after a successful upload
{
let dwnURL = task.snapshot.downloadURL;
let galleryRef = firebase.database().ref('gallery/'+albumkey);
let postkey = firebase.database().ref('gallery/'+albumkey).push().key;
updateAlbum={img:dwnURL};
firebase.database().ref('gallery/'+ albumkey+'/'+postkey).update(updateAlbum);
});
};
};
All the best!
I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.
I am using angularjs file uploader given at "https://github.com/nervgh/angular-file-upload", so my js code look like this:
var urls = ['url1', 'url2'];
var uploaders = $scope.uploaders = urls.map(function(url) {
return new FileUploader({url: url});
});
$http.get('url.php').then(function(resp) {
$scope.images = resp.data.images; // images array
uploaders[0].addToQueue($scope.images[0]);
// add first img to 1st uploader
var i;
for(i=1;i<$scope.images.length;i++){
uploaders[1].addToQueue($scope.images[i]);
}
// append other images to 2nd uploader
});
Now I can get uploaders[0].queue.length = 1 but not the other proerties like uploaders[0].queue[0].file.name ,
any suggestions?