我想实现一个用户界面,用户可以在其中选择图像,并且该图像会立即显示回给他们以供查看。用户必须单击“提交”才能将图像上传/保存到他们的个人资料中。
我在“立即显示回用户部分”方面遇到问题。
我使用带有以下标记和 Controller 的 Angular FormData:
标记
<input id="chooseFile" type="file" file-model="picFile" />
<img src="{{uploadedImage}}" /> <!-- this populates with filename but what is the path?? -->
Controller
angular.element('#chooseFile').change(function(){
var file = $scope.picFile; // this comes up "undefined" since file is still uploading when this is fired
$scope.uploadedImage = file.name;
});
上面的代码有两个主要问题(在评论中描述):
1) 在 Controller 中,file
出现 undefined
显然是因为即使是最小的文件也需要 >0 秒才能上传,而回调几乎是瞬时触发的。我使用 $timeout
让它工作,但这有点蹩脚。如何让回调等待文件上传?
2) 这个想法是上传文件并使用 Angular 的数据绑定(bind)将其显示在 img
标记中。这是有效的,因为 src
填充了文件名,但 img 的路径是什么。缓存中的某个临时位置或其他东西?显然我还没有设置移动文件的路径。
感谢任何帮助!
最佳答案
我也需要这个功能,一些我如何设法立即显示图像的方法。
angular.module('HelloWorldApp', [])
.controller('HelloWorldController', function($scope) {
$scope.uploadavtar = function(files) {
//var fd = new FormData();
//Take the first selected file
//fd.append("file", files[0]);
var imagefile = document.querySelector('#file');
if (imagefile.files && imagefile.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#temp_image')
.attr('src', e.target.result);
};
reader.readAsDataURL(imagefile.files[0]);
this.imagefile = imagefile.files[0];
}else{
console.log("Image not selected");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="HelloWorldApp">
<div ng-controller="HelloWorldController">
<input type="file" id="file" onchange="angular.element(this).scope().uploadavtar(this.files)"/>
</div>
<img src="" id="temp_image" width="100">
<div>
</div>
</div>
我使用的是 laravel
+ Angularjs
所以另一个存储图像的相关帖子是:https://stackoverflow.com/a/34830307/2815635
关于javascript - Angular上传图像并显示给用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42754355/