Вот моя форма HTML:
<form name="myForm" ng-submit="">
<input ng-model='file' type="file"/>
<input type="submit" value='Submit'/>
</form>
Я хочу загрузить изображение с локального компьютера и хочу прочитать содержимое загруженного файла. Все это я хочу использовать с помощью AngularJS.
Когда я пытаюсь напечатать значение $scope.file
, оно появляется как undefined.
Некоторые из ответов здесь предлагают использовать FormData()
, но, к сожалению, это объект браузера, недоступный в Internet Explorer 9 и ниже. Если вам нужно поддерживать эти старые браузеры, вам понадобится стратегия резервного копирования, например, с помощью <iframe>
или Flash.
Существует уже много модулей Angular.js для выполнения загрузки файлов. Эти два имеют явную поддержку для старых браузеров:
И некоторые другие варианты:
Один из них должен соответствовать вашему проекту или может дать вам некоторое представление о том, как его кодировать самостоятельно.
Самый простой способ - использовать API HTML5, а именно FileReader
HTML довольно прост:
<input type="file" id="file" name="file"/>
<button ng-click="add()">Add</button>
В контроллере определите метод 'add':
$scope.add = function() {
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e) {
var data = e.target.result;
//send your binary data via $http or $resource or do anything else with it
}
r.readAsBinaryString(f);
}
Совместимость с браузером
Настольные браузеры
Firefox (Gecko) 3.6 (1.9.2), Chrome 7, Интернет Explorer * 10, Opera * 12.02, Safari 6.0.2
Мобильные браузеры
Firefox (Gecko) 32, Chrome 3, Internet Explorer * 10, Opera * 11.5, Safari 6.1
Примечание: метод readAsBinaryString() устарел и readAsArrayBuffer() следует использовать вместо этого.
onloadend
обратного вызова onloadend
. Вам не нужна библиотека для использования этого API, она уже есть в вашем браузере (если вы не используете очень старый). Надеюсь это поможет.
Это путь 2015 года, без сторонних библиотек. Работает во всех последних браузерах.
app.directive('myDirective', function (httpPostFactory) {
return {
restrict: 'A',
scope: true,
link: function (scope, element, attr) {
element.bind('change', function () {
var formData = new FormData();
formData.append('file', element[0].files[0]);
httpPostFactory('upload_image.php', formData, function (callback) {
// recieve image name to use in a ng-src
console.log(callback);
});
});
}
};
});
app.factory('httpPostFactory', function ($http) {
return function (file, data, callback) {
$http({
url: file,
method: "POST",
data: data,
headers: {'Content-Type': undefined}
}).success(function (response) {
callback(response);
});
};
});
HTML:
<input data-my-Directive type="file" name="file">
PHP:
if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) {
// uploads image in the folder images
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = substr(md5(time()), 0, 10) . '.' . end($temp);
move_uploaded_file($_FILES['file']['tmp_name'], 'images/' . $newfilename);
// give callback to your angular code with the image src name
echo json_encode($newfilename);
}
js скрипка (только front-end) https://jsfiddle.net/vince123/8d18tsey/31/
Ниже приведен рабочий пример загрузки файла:
http://jsfiddle.net/vishalvasani/4hqVu/
В этой функции, называемой
setFiles
Из представления, которое будет обновлять массив файлов в контроллере
или
Вы можете проверить загрузку файла jQuery с помощью функции AngularJS
Вы можете добиться хорошей загрузки файлов и папок с помощью flow.js.
https://github.com/flowjs/ng-flow
Посмотрите демо здесь
http://flowjs.github.io/ng-flow/
Он не поддерживает IE7, IE8, IE9, поэтому вам в конечном итоге придется использовать уровень совместимости
Я попробовал все альтернативы, которые @Anoyz (правильный ответ) дает... и лучшее решение https://github.com/danialfarid/angular-file-upload
Некоторые функции:
Это отлично работает для меня. Вам просто нужно обратить внимание на инструкции.
На стороне сервера я использую NodeJs, Express 4 и промежуточное ПО Multer для управления многостраничным запросом.
nlzt9LJWRrAZEO3ZteZUOgGc
но без формата .png. Как добавить это?
Используйте событие onchange
, чтобы передать элемент входного файла в вашу функцию.
<input type="file" onchange="angular.element(this).scope().fileSelected(this)" />
Поэтому, когда пользователь выбирает файл, у вас есть ссылка на него без необходимости нажатия кнопки "Добавить" или "Загрузить".
$scope.fileSelected = function (element) {
var myFileSelected = element.files[0];
};
<form ng-controller = "myCtrl">
<input type = "file" file-model="files" multiple/>
<button ng-click = "uploadFile()">upload me</button>
<li ng-repeat="file in files">{{file.name}}</li>
</form>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
angular.module('myApp', []).directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.bind('change', function(){
$parse(attrs.fileModel).assign(scope,element[0].files)
scope.$apply();
});
}
};
}]).controller('myCtrl', ['$scope', '$http', function($scope, $http){
$scope.uploadFile=function(){
var fd=new FormData();
console.log($scope.files);
angular.forEach($scope.files,function(file){
fd.append('file',file);
});
$http.post('http://localhost:1337/mediaobject/upload',fd,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function(d){
console.log(d);
})
}
}]);
</script>
Я думаю, что это загрузка файла angular:
Легкая angular Директива JS для загрузки файлов.
Вот страница DEMO. Особенности
Легко с директивой
Html:
<input type="file" file-upload multiple/>
JS:
app.directive('fileUpload', function () {
return {
scope: true, //create a new scope
link: function (scope, el, attrs) {
el.bind('change', function (event) {
var files = event.target.files;
//iterate files since 'multiple' may be specified on the element
for (var i = 0;i<files.length;i++) {
//emit event upward
scope.$emit("fileSelected", { file: files[i] });
}
});
}
};
В директиве мы обеспечиваем создание новой области и затем прослушиваем изменения, внесенные в элемент ввода файла. Когда изменения обнаруживаются при генерации события во все области предков (вверх) с файлом в качестве параметра.
В вашем контроллере:
$scope.files = [];
//listen for the file selected event
$scope.$on("fileSelected", function (event, args) {
$scope.$apply(function () {
//add the file object to the scope files collection
$scope.files.push(args.file);
});
});
Затем в вашем вызове ajax:
data: { model: $scope.model, files: $scope.files }
http://shazwazza.com/post/uploading-files-and-json-data-in-the-same-request-with-angular-js/
Загрузка файлов и json в одно и то же время.
// FIRST SOLUTION
var _post = function (file, jsonData) {
$http({
url: your url,
method: "POST",
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
formData.append("file", data.files);
return formData;
},
data: { model: jsonData, files: file }
}).then(function (response) {
;
});
}
// END OF FIRST SOLUTION
// SECOND SOLUTION
// İf you can add plural file and İf above code give an error.
// You can try following code
var _post = function (file, jsonData) {
$http({
url: your url,
method: "POST",
headers: { 'Content-Type': undefined },
transformRequest: function (data) {
var formData = new FormData();
formData.append("model", angular.toJson(data.model));
for (var i = 0; i < data.files.length; i++) {
// add each file to
// the form data and iteratively name them
formData.append("file" + i, data.files[i]);
}
return formData;
},
data: { model: jsonData, files: file }
}).then(function (response) {
;
});
}
// END OF SECOND SOLUTION
Вы можете использовать FormData
объект, который является безопасным и быстрым:
// Store the file object when input field is changed
$scope.contentChanged = function(event){
if (!event.files.length)
return null;
$scope.content = new FormData();
$scope.content.append('fileUpload', event.files[0]);
$scope.$apply();
}
// Upload the file over HTTP
$scope.upload = function(){
$http({
method: 'POST',
url: '/remote/url',
headers: {'Content-Type': undefined },
data: $scope.content,
}).success(function(response) {
// Uploading complete
console.log('Request finished', response);
});
}
Элемент <input type=file>
по умолчанию не работает с директивой ng-model. Для этого нужна настраиваемая директива:
ng-model
1
angular.module("app",[]);
angular.module("app").directive("filesInput", function() {
return {
require: "ngModel",
link: function postLink(scope,elem,attrs,ngModel) {
elem.on("change", function(e) {
var files = elem[0].files;
ngModel.$setViewValue(files);
})
}
}
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="app">
<h1>AngularJS Input `type=file` Demo</h1>
<input type="file" files-input ng-model="fileList" multiple>
<h2>Files</h2>
<div ng-repeat="file in fileList">
{{file.name}}
</div>
</body>
$http.post
из FileList$scope.upload = function(url, fileList) {
var config = { headers: { 'Content-Type': undefined },
transformResponse: angular.identity
};
var promises = fileList.map(function(file) {
return $http.post(url, file, config);
});
return $q.all(promises);
};
При отправке POST с File object важно установить 'Content-Type': undefined
. метод отправки XHR затем обнаружит File object и автоматически установите тип содержимого.
Я знаю, что это поздняя запись, но я создал простую директиву загрузки. Которые вы можете получить в кратчайшие сроки!
<input type="file" multiple ng-simple-upload web-api-url="/api/Upload" callback-fn="myCallback" />
ng-simple-upload подробнее о Github с примером, использующим веб-API.
Вы можете рассмотреть IaaS для загрузки файлов, например Uploadcare. Для него есть пакет Angular: https://github.com/uploadcare/angular-uploadcare
Технически это реализовано как директива, предоставляющая различные варианты загрузки и манипуляции с загруженными изображениями в виджетах:
<uploadcare-widget
ng-model="object.image.info.uuid"
data-public-key="YOURKEYHERE"
data-locale="en"
data-tabs="file url"
data-images-only="true"
data-path-value="true"
data-preview-step="true"
data-clearable="true"
data-multiple="false"
data-crop="400:200"
on-upload-complete="onUCUploadComplete(info)"
on-widget-ready="onUCWidgetReady(widget)"
value="{{ object.image.info.cdnUrl }}"
/>
Дополнительные параметры конфигурации для игры: https://uploadcare.com/widget/configure/
http://jsfiddle.net/vishalvasani/4hqVu/ отлично работает в chrome и IE (если вы немного обновляете CSS в фоновом изображении). Это используется для обновления индикатора выполнения:
scope.progress = Math.round(evt.loaded * 100 / evt.total)
но в FireFox angular [percent] данные не обновляются в DOM успешно, хотя файлы успешно загружаются.
load
и, если длина вычислима, запустить событие прогресса, чтобы указать успешную загрузку. github.com/danialfarid/angular-file-upload уже позаботится об этом.
Я прочитал весь поток, и решение API HTML5 выглядело лучше всего. Но он меняет мои двоичные файлы, разлагая их так, как я не исследовал. Идеальное решение для меня:
HTML:
<input type="file" id="msds" ng-model="msds" name="msds"/>
<button ng-click="msds_update()">
Upload
</button>
JS:
msds_update = function() {
var f = document.getElementById('msds').files[0],
r = new FileReader();
r.onloadend = function(e) {
var data = e.target.result;
console.log(data);
var fd = new FormData();
fd.append('file', data);
fd.append('file_name', f.name);
$http.post('server_handler.php', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
console.log('success');
})
.error(function(){
console.log('error');
});
};
r.readAsDataURL(f);
}
Серверная сторона (PHP):
$file_content = $_POST['file'];
$file_content = substr($file_content,
strlen('data:text/plain;base64,'));
$file_content = base64_decode($file_content);
Это должно быть обновление/комментарий к ответу @jquery-guru, но, поскольку у меня недостаточно ответов, он пойдет сюда. Он исправляет ошибки, которые теперь генерируются кодом.
https://jsfiddle.net/vzhrqotw/
В основном это изменение:
FileUploadCtrl.$inject = ['$scope']
function FileUploadCtrl(scope) {
To:
app.controller('FileUploadCtrl', function($scope)
{
Не стесняйтесь перемещаться в более подходящее место, если это необходимо.
Рабочий пример с использованием простой директивы (ng-file-model):
.directive("ngFileModel", [function () {
return {
$scope: {
ngFileModel: "="
},
link: function ($scope:any, element, attributes) {
element.bind("change", function (changeEvent:any) {
var reader = new FileReader();
reader.onload = function (loadEvent) {
$scope.$apply(function () {
$scope.ngFileModel = {
lastModified: changeEvent.target.files[0].lastModified,
lastModifiedDate: changeEvent.target.files[0].lastModifiedDate,
name: changeEvent.target.files[0].name,
size: changeEvent.target.files[0].size,
type: changeEvent.target.files[0].type,
data: changeEvent.target.files[0]
};
});
}
reader.readAsDataURL(changeEvent.target.files[0]);
});
}
}
}])
и используйте FormData
для загрузки файла в вашу функцию.
var formData = new FormData();
formData.append("document", $scope.ngFileModel.data)
formData.append("user_id", $scope.userId)
все кредиты идут https://github.com/mistralworks/ng-file-model
Я столкнулся с небольшой пробкой, которую вы можете проверить здесь: https://github.com/mistralworks/ng-file-model/issues/7
Наконец, здесь разветвленное репо: https://github.com/okasha93/ng-file-model/blob/patch-1/ng-file-model.js
Мы использовали HTML, CSS и AngularJS. В следующем примере показано, как загрузить файл с помощью AngularJS.
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
app.directive('ngUpload', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var options = {};
options.enableControls = attrs['uploadOptionsEnableControls'];
// get scope function to execute on successful form upload
if (attrs['ngUpload']) {
element.attr("target", "upload_iframe");
element.attr("method", "post");
// Append a timestamp field to the url to prevent browser caching results
element.attr("action", element.attr("action") + "?_t=" + new Date().getTime());
element.attr("enctype", "multipart/form-data");
element.attr("encoding", "multipart/form-data");
// Retrieve the callback function
var fn = attrs['ngUpload'].split('(')[0];
var callbackFn = scope.$eval(fn);
if (callbackFn == null || callbackFn == undefined || !angular.isFunction(callbackFn))
{
var message = "The expression on the ngUpload directive does not point to a valid function.";
// console.error(message);
throw message + "\n";
}
// Helper function to create new i frame for each form submission
var addNewDisposableIframe = function (submitControl) {
// create a new iframe
var iframe = $("<iframe id='upload_iframe' name='upload_iframe' border='0' width='0' height='0' style='width: 0px; height: 0px;
border: none; display: none' />");
// attach function to load event of the iframe
iframe.bind('load', function () {
// get content - requires jQuery
var content = iframe.contents().find('body').text();
// execute the upload response function in the active scope
scope.$apply(function () { callbackFn(content, content !== "" /* upload completed */); });
// remove iframe
if (content != "") // Fixes a bug in Google Chrome that dispose the iframe before content is ready.
setTimeout(function () { iframe.remove(); }, 250);
submitControl.attr('disabled', null);
submitControl.attr('title', 'Click to start upload.');
});
// add the new iframe to application
element.parent().append(iframe);
};
// 1) get the upload submit control(s) on the form (submitters must be decorated with the 'ng-upload-submit' class)
// 2) attach a handler to the controls' click event
$('.upload-submit', element).click(
function () {
addNewDisposableIframe($(this) /* pass the submit control */);
scope.$apply(function () { callbackFn("Please wait...", false /* upload not completed */); });
var enabled = true;
if (options.enableControls === null || options.enableControls === undefined || options.enableControls.length >= 0) {
// disable the submit control on click
$(this).attr('disabled', 'disabled');
enabled = false;
}
$(this).attr('title', (enabled ? '[ENABLED]: ' : '[DISABLED]: ') + 'Uploading, please wait...');
// submit the form
$(element).submit();
}
).attr('title', 'Click to start upload.');
}
else
alert("No callback function found on the ngUpload directive.");
}
};
});
<form class="form form-inline" name="uploadForm" id="uploadForm"
ng-upload="uploadForm12" action="rest/uploadHelpFile" method="post"
enctype="multipart/form-data" style="margin-top: 3px;margin-left:
6px"> <button type="submit" id="mbUploadBtn" class="upload-submit"
ng-hide="true"></button> </form>
@RequestMapping(value = "/uploadHelpFile", method =
RequestMethod.POST) public @ResponseBody String
uploadHelpFile(@RequestParam(value = "file") CommonsMultipartFile[]
file,@RequestParam(value = "fileName") String
fileName,@RequestParam(value = "helpFileType") String
helpFileType,@RequestParam(value = "helpFileName") String
helpFileName) { }
<form id="csv_file_form" ng-submit="submit_import_csv()" method="POST" enctype="multipart/form-data">
<input ng-model='file' type="file"/>
<input type="submit" value='Submit'/>
</form>
В угловом контроллере JS
$scope.submit_import_csv = function(){
var formData = new FormData(document.getElementById("csv_file_form"));
console.log(formData);
$.ajax({
url: "import",
type: 'POST',
data: formData,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
success: function(result, textStatus, jqXHR)
{
console.log(result);
}
});
return false;
}
простыми словами
в Html - добавить только код ниже
<form name="upload" class="form" data-ng-submit="addFile()">
<input type="file" name="file" multiple
onchange="angular.element(this).scope().uploadedFile(this)" />
<button type="submit">Upload </button>
</form>
в контроллере. Эта функция вызывается, когда вы нажимаете кнопку "Загрузить файл" . он будет загружать файл. вы можете отключить его.
$scope.uploadedFile = function(element) {
$scope.$apply(function($scope) {
$scope.files = element.files;
});
}
добавить больше в контроллеры - под кодом добавить в функцию. Эта функция вызывается, когда вы нажимаете кнопку, которая используется , чтобы попасть в api (POST). он отправит файл (который загружен) и данные формы на бэкэнд.
var url = httpURL + "/reporttojson"
var files=$scope.files;
for ( var i = 0; i < files.length; i++)
{
var fd = new FormData();
angular.forEach(files,function(file){
fd.append('file',file);
});
var data ={
msg : message,
sub : sub,
sendMail: sendMail,
selectUsersAcknowledge:false
};
fd.append("data", JSON.stringify(data));
$http.post(url, fd, {
withCredentials : false,
headers : {
'Content-Type' : undefined
},
transformRequest : angular.identity
}).success(function(data)
{
toastr.success("Notification sent successfully","",{timeOut: 2000});
$scope.removereport()
$timeout(function() {
location.reload();
}, 1000);
}).error(function(data)
{
toastr.success("Error in Sending Notification","",{timeOut: 2000});
$scope.removereport()
});
}
в этом случае.. я добавил код ниже как данные формы
var data ={
msg : message,
sub : sub,
sendMail: sendMail,
selectUsersAcknowledge:false
};
HTML
<input type="file" id="file" name='file' onchange="angular.element(this).scope().profileimage(this)" />
добавьте метод 'profileimage()' к вашему контроллеру
$scope.profileimage = function(selectimage) {
console.log(selectimage.files[0]);
var selectfile=selectimage.files[0];
r = new FileReader();
r.onloadend = function (e) {
debugger;
var data = e.target.result;
}
r.readAsBinaryString(selectfile);
}
Выше принятый ответ не совместим с браузером. Если кто-то имеет проблему совместимости, попробуйте это.
Просмотр кода
<div ng-controller="MyCtrl">
<input type="file" id="file" name="file"/>
<br>
<button ng-click="add()">Add</button>
<p>{{data}}</p>
</div>
Код контроллера
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.data = 'none';
$scope.add = function(){
var f = document.getElementById('file').files[0],
r = new FileReader();
r.onloadend = function(e){
var binary = "";
var bytes = new Uint8Array(e.target.result);
var length = bytes.byteLength;
for (var i = 0; i < length; i++)
{
binary += String.fromCharCode(bytes[i]);
}
$scope.data = (binary).toString();
alert($scope.data);
}
r.readAsArrayBuffer(f);
}
}