Angular 上传图片并显示给用户

Angular upload image and display to user

我想实现一个 UI,用户可以在其中选择一个图像,该图像会立即显示给他们以供查看。用户必须单击 "submit" 才能将图像 upload/save 添加到他们的个人资料中。

我遇到了 "instantly display back to the user part" 的问题。

我正在使用 angular 具有以下标记和控制器的 FormData:

标记

<input id="chooseFile" type="file" file-model="picFile" />

<img src="{{uploadedImage}}" /> <!-- this populates with filename but what is the path?? -->

控制器

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;

});

上面的代码有 2 个主要问题(在评论中描述):

1) 在控制器中,file 出现 undefined 显然是因为即使是最小的文件也需要 >0 秒才能上传,而回调几乎是瞬间触发的。我使用 $timeout 让它工作,但这有点蹩脚。如何让回调等到文件上传?

2) 想法是上传文件并使用 Angular 的数据绑定将其显示在 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 所以另一个相关的 post 存储图像是: