gpt4 book ai didi

javascript - Angular 上传图像并显示给用户

转载 作者:行者123 更新时间:2023-11-29 23:51:09 25 4
gpt4 key购买 nike

我想实现一个用户界面,用户可以在其中选择一张图片,该图片会立即显示给他们以供查看。用户必须单击“提交”才能将图像上传/保存到他们的个人资料中。

我在“立即显示回用户部分”方面遇到问题。

我正在使用具有以下标记和 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;

});

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

1) 在 Controller 中,file 出现 undefined 显然是因为即使是最小的文件也需要 >0s 才能上传,而回调几乎是瞬间触发的。我使用 $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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com