我想用 AngularJs 上传一个文件(这样的图像)...我读到 AngularJs 不支持标签输入类型 ="file" 所以我读到我需要自定义指令...我想获取输入文件并使用它在同一页 html 上显示预览(缩略图),并在 Controller 中将文件上传到服务器上...在我的页面 html 中,我写了这段代码:
<body ng-controller="myController">
<h1>Select file</h1>
<input type="file" file-model="myFile" />
<div>
<h2>File content is:</h2>
<pre>{{ content }}</pre>
</div>
</body>
我写了这个指令:
var modulo = angular.module('myApp', []);
modulo.directive('fileModel', function () {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('change', function (event) {
var file = event.target.files[0];
scope.$emit("fileSelected", file);
});
}
};
});
这是我的 Controller :
modulo.controller('myController', function ($scope) {
$scope.$on('fileSelected', function (event, args) {
$scope.content(args.file);
console.log(args.file);
});
});
此代码不起作用...有解决方案吗?哪里出错了?
最佳答案
错误在你的指令中
检查这个,我在我的应用程序中使用了相同的指令
.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]);
});
});
}
};
}
this is my html to
input(type="file", file-model="myFile", accept="image/*", image="image", id='fileInput')
这是我为处理上传而创建的一个小服务
function fileUpload (file, uploadUrl) {
var cropedImage = dataURItoBlob(file);
var fileData = new FormData(),
uploadedImage = '';
fileData.append('fileUpload', cropedImage);
return $http({
withCredentials: true,
method: "POST",
url: uploadUrl,
data: fileData,
headers: {'Content-Type': undefined},
transformRequest: angular.identity
});
}
试试这个,它对我有用
关于javascript - 使用 AngularJs 上传文件/图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29793650/