nervgh / angular-file-upload Goto Github PK
View Code? Open in Web Editor NEW[ALMOST NOT MAINTAINED] Angular File Upload is a module for the AngularJS framework
License: MIT License
[ALMOST NOT MAINTAINED] Angular File Upload is a module for the AngularJS framework
License: MIT License
Hi,
When I' am making the call $fileUploader.create and in the url I' am passing the URL to a ASP.NET Web API, the http response I' am getting is 204 No Content.
// create a uploader with options
var uploader = $scope.uploader = $fileUploader.create({
scope: $scope, // to automatically update the html. Default: $rootScope
url: '/api/upload',
method: 'POST',
headers: headers,
filters: [
function (item) { // first user filter
console.info('filter1');
return true;
}
]
});
My Web API method signature is:
public void Post(HttpPostedFileBase files)
Do I need to specify anything else in the property for this files collection to be posted ?
I recently integrated this with a Rails app, and I wanted to write some documentation for setting the CSRF token in Rails.
Should I make a pull request to the README, or would a Wiki page be better?
Сообственно в вашем примере http://nervgh.github.io/pages/angular-file-upload/examples/simple/ в инспекторе не печатается 'After adding all files ...'
Chrome 32.
Here's what it looks like to me on the example application:
This seems similar to this question on the jQuery-File-Upload FAQ, but I'm not sure how to work around it in angular-file-upload.
Суть проблемы:
Перед отправкой каждого файла который выбрал пользователь я должен создать "место' для него отдельным ajax запросом. Результатом будет url на который надо запостить файл.
uploader.bind('afteraddingfile', function (event, item) {
getFileUrl().success(function(fileUrl) {
item.url = fileUrl;
item.upload()
})
});
Проблема в том, что если событие success отрабатывается в тот момент когда uploader в состоянии isUploading, то upload() никогда не отработает.
Как быть? Посоветуй, пожалуйста.
hi,
awesome library,
does it support Chunk Uploading ?
thanks in advanced.
Hello,
Angular-file-upload has worked great so far. My only question is: is there a way to upload all the files in the queue in one request rather than send a request per file?
Thanks for your help!
I use bower to install your angular-file-upload, when i do "bower update angular-file-upload" the local version stays at 0.2.7
i need to update because cancelAll() doesn't work!
thanks in advance!
Building the library in jenkins is failing because of the wrong dependency that the angular has in bower.json:
"angular": "~1.2.0-rc.1",
Now that git tag was renamed to
"1.2.0rc.1"
as seen here
https://github.com/angular/angular.js/tree/v1.2.0rc1
Cheers!
I have a simple
would be nice if the value (-> file name) changes when selecting a file
A solution could be this: http://stackoverflow.com/questions/18383446/how-to-validate-form-with-inputtype-file-in-angularjs
Делал загрузку файлов по вашему примеру, но у меня открывается модальное окно от "angular-ui/bootstrap".
Открываю модальное окно, все окей, файлы добавляются в список и загружаются..
https://dl.dropboxusercontent.com/u/21063986/other/afl-modal.jpg
Далее: закрываю модальное окно => открываю модальное заново => выбираю файл => фильтр срабатывает => файл в список не добавился....
Вот тут я и задумался :(
I'm trying to upload some data along with the files, but I don't seem to be able to. I've tried the following:
var uploader = $fileUploader.create({
scope: $scope,
url: 'http://localhost/projects/temp-upload/upload.php',
formData: {
myData: 'hello' // <--- Data for every file
},
filters: [
function( item ) {
console.log(item);
item.formData = { myFileData : 'hello2' } // <-- Data for certain files
return true;
}
],
autoUpload: true,
removeAfterUpload: true
});
The files upload OK, but the data is lost. What am I doing wrong? 😦
Thank you for the component, it seems to be very nice and I would love to use it in my project. I took the example page and inserted it almost without changes to my application. However while testing it I have found a strange behavior.
Everything works as supposed to when the form (actually the example page) is displayed for the first time. When I navigate to another page and then back to the upload form page the page does not update the view – I mean after selecting a file (via the button or drop) the triggers from the demo controller get fired and in the console I can see the queue correctly updated, bud the page still shows ‘Queue length: 0’ and an empty file list. Moreover, according to the logs from the console the queue contains items from the ‘first visit’ of the upload form page.
Do you have an idea what is going on here? Shall I re-set / re-init the component after repeating visit of the page?
Thank you very much.
I have created a service which uses your $fileUploader. This get function will be called in a controller! This controller loads depending on user interaction. So I thought I create an new uploader (with a new timestamp) everytime. BUT there are somehow old listeners on this 'new' uploader, with old timestamps.. how can I assert that there are only the needed listeners available?
I hope you know what I mean!
/**
* Need to set the http headers like in config.js because
* angular-file-uploader doesn't use $http
*/
lingohub.service('fileUploader', ['$fileUploader', '$cookies', function ($fileUploader, $cookies) {
this.get = function(url, alias) {
var uploader = $fileUploader.create({
headers: {
"X-AUTH-TOKEN": $cookies["AUTH-TOKEN"],
"X-AUTH-EMAIL": $cookies["AUTH-EMAIL"],
"X-CSRF-TOKEN": $cookies["CSRF-TOKEN"]
},
url: url
});
if(angular.isDefined(alias)) {
uploader.alias = alias;
}
// remove old listeners
// angular.forEach(uploader.scope.$$listeners, function(value, key){
// if (/(\d+):.*/.test(key)) {
// var timestamp = parseInt(RegExp.$1);
// if(timestamp !== uploader._timestamp) {
// delete uploader.scope.$$listeners[key];
// }
// }
// });
// just keep last item in queue --> for single file upload
uploader.bind('afteraddingfile', function (event, item) {
if(uploader.queue.length > 1) {
uploader.queue.shift();
}
});
return uploader;
};
}]);
Для моей задачи требуется динамическое количество форм загрузки картинок. Пытаюсь это реализовать, создаю несколько аплоадеров, но при добавлении фотографии в один, она добавляется и в другие.
Как можно этого избежать? буду благодарен за любую помощь. В Angular я новичок.
I need have a page to show all the images that I uploaded before. So I can remove old images and add new image. I want to do this in the queue the same way when I uploaded them before. How to do this?
Thanks.
I noticed issue #25 suggests creating multiple scopes by creating controllers. This is not feasible with ngRepeat. Any other trick?
Working with $rootScope for uploader may create restrictions in future.
Would be nice to be able to restrict file extensions ie (png|jpeg|jpg|gif)
Or by max size (1MB)
with error messages if possible.
Если выбрать файл (1) и удалить его, то повторно выбрать тот же файл (1) невозможно. Необходимо выбирать другой файл (2) и только после этого можно добавить файл (1). Возможно это нюанс самого поля ввода. Интересно выяснить данный вопрос.
While i try to upload any video of size above 60mb, it never uploads rather the uploading gets restarted at some 50% and then it will show error uploading
Суть проблемы:
Перед тем как загружать файлы, делается проверка:
if ($scope.uploader.getNotUploadedItems().length) {
$scope.uploader.uploadAll();
...
}
Если файл не загрузился, по каким либо причинам - всё равно происходит
_error: function (event, xhr, item, response) {
item.isUploaded = true;
item.isUploading = false;
item.uploader.trigger('error', xhr, item, response);
},
То есть
item.isUploaded = true;
И в таком случае метод getNotUploadedItems возвращает пустой массив, и повторная отправка не срабатывает.
Так и должно быть ? Я выбрал не верную стратегию ?
Подскажите пожалуйста как загружать файлы повторно, если они не загрузились с первого раза?
Hi!
How to embbed a CSRF TOKEN in form data?
app.controller('UploadPhoto', function($scope, $http, $fileUploader, CSRF_TOKEN)
{
// create a uploader with options
var uploader = $scope.uploader = $fileUploader.create({
scope: $scope, // to automatically update the html. Default: $rootScope
url: '/profile/me/photo',
formData: [
{ csrf_token: CSRF_TOKEN }
],
filters: [
function (item) { // first user filter
console.info('filter1');
return true;
}
]
});
Not work...
Help?
I'm trying to upload an icon and an image file, both have to be a specific height and width that is being verified before upload.
I was wondering if it is possible to have two different input boxes for this that hook up to two different uploaders.
Is it possible to show already uploaded files when reload?
Looks like uploadAll goes to infinite loop if there is some problem with one of the files and server returns non 200 status for it.
i have uploader as follows ...
.controller('fileUploadController', function ($scope, $fileUploader) {
'use strict';
$scope.fileName = "Choose File";
$scope.currentFile = {};
$scope.isFormSubmit = false;
$scope.headValue = [];
$scope.progressComplete = 0;
var uploader = $scope.uploader = $fileUploader.create({
scope: $scope,
url: uploadFile,
autoUpload : true,
headers: {fileName: $scope.fileName},
formData: [
{ fileName: $scope.fileName}
],
filters: [
function (item) { // first user filter
console.info('filter1');
return true;
}
]
});
Thank You,
While updating to latest release I spotted this on the log:
bower mismatch Version declared in the json (0.2.5) is different than the resolved one (0.2.7)
Yes/no? Comments are optional.
Like MIT or Apache ?
AngularJs is MIT
https://github.com/angular/angular.js/blob/master/LICENSE
I tried to remove it from the queue but the upload goes on. I suppose we need to call xhr.abort() but the API does not seem to allow that.
Haven’t you thought about implementing it?
Thanks
This code "this._observer.$on(this._timestamp + ':' + event, handler.bind(this))" return unsubscribe function.
Thanks.
Hi! Thanks for this module, looks great 😄
I was wondering if it's possible to upload all files simultaneously instead of one by one. If so, how do I configure the component?
Привет, вот такая вот проблема:
$scope.uploader.bind( 'error', function( event, xhr, item, response ) {
$globalMessage.add(response.message, 'danger');
});
response undefined
PS: в документации думаю лучше изменить items на item в beforeupload, а то вводит в заблуждение:
beforeupload function( event, items ) {
Спасибо :)
Hi,
I'm new to github and new to Angular JS (but not new to Javascript). So I hope it's acceptable to ask these kind of questions in the "issues" section. I didn't know where else to ask.
I found this component because I need image uploads on my profile page and it's an excellent component, but I can't seem to work out how to use it for my needs. It's a bit complicated so I drew a picture of what I want my form to look like.
As you can see, it has two fields, each of which needs to allow one photo to be added to the queue. Each one has a preview thumbnail and each one needs to post to the back end with some metadata attached to say whether it is a profile pic or a pet pic.
I need to use one uploader, not two, because the progress bar at the bottom shows the progress of all files being uploaded, also, because I need to bind to the 'completeall' event so that I can post the rest of the form to another handler once the uploads are complete.
So, just one uploader and one queue, but I have run into the following problems....
Each can upload multiple files, even if I take the multiple attribute off it can still add multiple files to the queue if you add them one at a time.
The chosen file name is "no file chosen" even once you've chosen a file. This happens in the demos, not just my code.
Not sure how to get the preview directive working to show the file which has been uploaded through the corresponding
Once the 'completeall' is called, my server script will send an ID back for each image upload which then needs to be stored on the scope so I can add it to a database. Don't have a clue how to get this info which is passed back.
This one I think I have solved, I can add form data to say whether it's a profile pic or a pet pic by doing this, , right?
I need to style the elements so that it uses javascript to get the file name and insert it into a text box, and trigger the browse button when the user focuses the textbox?
I think the main problems are 1, 2, 3 and 4 becuase I have an idea of how to solve 5 and 6.
I know this is a cheeky request (and a long one) because this is a free/open source component, but I'd really appreciate some help from somebody, even just a pointer in the right direction!
Thanks, Jon
i have the following code:
if(uploader.queue.length) {
var firstItem = uploader.queue[0];
uploader.uploadItem(firstItem);
// successful upload
uploader.bind('success', function (event, xhr, item) {
console.log("success")
uploader.clearQueue();
var response = angular.fromJson(xhr.response);
successCallback(response);
});
// unsuccessful upload
uploader.bind('error', function (event, xhr, item) {
var response = angular.fromJson(xhr.response);
errorCallback(response);
});
}
it works just fine, but not in a special case:
when there is not a failing error before than it's just triggered once!
i hope you know what I mean and can help me ;)
Conflict with this plugin https://github.com/codef0rmer/angular-dragdrop
Uncaught TypeError: Cannot read property 'files' of undefined
First of all: awesome script.
I would like to ask how can i allow only one file (no multiple) to drag and drop?
Or maybe in controller
uploader.bind('afteraddingall', function (event, items) {
console.info('After adding all files', items);
});
Somehow remove all after drop except one?
And i think i am doing something wrong
var data = new Array();
data[0] = "/path";
url: 'upload.php',
formData: data
In network -> upload i see:
Request payload:
------WebKitFormBoundarycwIxQAfgsJMbgaI5
Content-Disposition: form-data; name="0"
/
------WebKitFormBoundarycwIxQAfgsJMbgaI5
Content-Disposition: form-data; name="1"
u
------WebKitFormBoundarycwIxQAfgsJMbgaI5
Content-Disposition: form-data; name="2"
p
------WebKitFormBoundarycwIxQAfgsJMbgaI5
Content-Disposition: form-data; name="3"
l
------WebKitFormBoundarycwIxQAfgsJMbgaI5
Content-Disposition: form-data; name="4"
o
------WebKitFormBoundarycwIxQAfgsJMbgaI5
Content-Disposition: form-data; name="5"
a
------WebKitFormBoundarycwIxQAfgsJMbgaI5
Content-Disposition: form-data; name="6"
d
------WebKitFormBoundarycwIxQAfgsJMbgaI5
Content-Disposition: form-data; name="7"
s
------WebKitFormBoundarycwIxQAfgsJMbgaI5
Content-Disposition: form-data; name="8"
/
Thank you
I guess this is more a feature request.
I would have just added it and then did a pull request but I did not know how to best do it.
It would be neat if we could preview an image while it is uploading. Here is how I did it using the events.
https://gist.github.com/cloudmanic/92adaaffed4216985233
Even if you do not want this as part of the core I thought I would share as it might be helpful to someone else.
Hello, the plugin is great!
However, there is an issue having multiple instances of the plugin running. Aswell when i try to reapply directive multiple times during view changes - file upload keeps bound to original scope.
I have tracked the problem and it looks like it is being caused by applying listener to rootScope.
After changing it to local scope i was able to have multiple reappliances of the directive.
Is there any specific reason to use rootscope for events?
Вечер добрый. Такой вопрос, возможно ли, используя эту библиотеку, создать несколько Drop объектов прb перетаскивании на которые файлa он бы загружались по разным (привязанным к конкретному объекту URL-ам).
К примеру таблица, где для каждой строки свой url для загрузки?
Hi All,
I tested the example in ie9 and is not working. What do you want to mean with: " It supports native HTML5 uploads, but degrades to a legacy iframe upload method for older browsers"?
Thanks, Cristian.
I'm using this on top of a fully Restful service and because of this sometimes I need to use PUT instead of POST.
I've created a pull request with my changes. In addition to allowing you to specify the method on an item I've also made a response of 201 a success code.
to perform uploader.bind().bind()...
your thougths ?
Is it ok, that i can't add csv files(maybe some others flletypes)?
Is there any reason you wouldn't want the uploader to be a Singleton? That would solve the multiple instance problem.
Is it possible to update the URL for the uploader? I would like to post some data first, retrieve the ID in the response, then upload the files to the server using a URL containing the ID returned from the server.
Hello!
I have been trying for a while to get the file uploading working in IE8 (IE8 document mode). The problem is when angular-file-uploader tries to access the iframe content IE reports "access denied". The file upload is being made within the same domain. Is IE8 supported by angular-file-upload?
Im using:
Здравствуйте!
Есть следующий код:
scope.uploader.bind('complete', function(event, xhr, item, response) {
...
});
Событие срабатывает, но в разных браузерах в переменной response я получаю разный результат. В Chrome - это объект:
{
Id: 244,
Name: 'DSC04749.jpg'
}
а в FireFox - это просто xml-строка:
[BinaryDataDto xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/BusinessPortal.Contracts.Dto"][Id]244[/Id][Name]DSC04749.jpg[/Name][/BinaryDataDto]
(в строке xml заменил фигурные скобки на квадратные)
Почему так?
Серверная часть (формирующая ответ) реализована на Asp.NET Web API.
How can I test uploading with this plug-in and ng-scenario e2e tests?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.