【问题标题】:AngularJS image upload preview without directive没有指令的AngularJS图像上传预览
【发布时间】:2015-03-02 18:28:26
【问题描述】:

我正在通过服务上传文件:

var addFile = function(files) {
  var deferred = $q.defer();
  var fd = new FormData();
  fd.append("file", files[0]);
  $http.post("/files", fd, {
      ***
    })
    .success(function(data, status, headers, config) {
      ***
    })
    .error(function(err, status) {
      ***
    });
    ***
};

在控制器中我有类似的东西:

uplService.addFile($scope.files).then(function(url) {
  $scope.news.Photo = url;
});

在 HTML 视图中:

<input type="file" name="file" onchange="angular.element(this).scope().photoChanged(this.files)" />

在此之前我在旅途中上传文件,当我选择文件时它直接进入服务器,但现在我需要在选择它时将它显示在我的表单中,但稍后上传,我在网络上看到的只是使用指令,但我如何在不使用指令的情况下组织它?

【问题讨论】:

标签: javascript angularjs image


【解决方案1】:

你可以在你的控制器中尝试这个来在这里传递你的文件对象吗:

$scope.fileReaderSupported = window.FileReader != null;
$scope.photoChanged = function(files){
    if (files != null) {
        var file = files[0];
    if ($scope.fileReaderSupported && file.type.indexOf('image') > -1) {
        $timeout(function() {
            var fileReader = new FileReader();
            fileReader.readAsDataURL(file);
            fileReader.onload = function(e) {
                $timeout(function(){
                    $scope.thumbnail.dataUrl = e.target.result;
                });
            }
        });
    }
}
};

在视图中

<img ng-show="thumbnail.dataUrl != null" ng-src="{{ thumbnail.dataUrl }}" class="thumb">

demo here

希望有帮助

【讨论】:

    【解决方案2】:

    看了这篇article,帮我解决了上传图片的问题。

    如果你想显示你选择的文件,试试这个:

    <img data-ng-src="data:image/png;base64,{{news.Photo}}" id="photo-id"/>
    

    解释

    您在 Model/ViewModel/Class 中的图像属性必须是字节数组,例如

    public byte[] Photo { get; set; }
    

    data:image/jpeg;base64 定义了来自news.Photo 的字节数组,因此它可以在客户端浏览器上正确呈现。

    在您的情况下,$scope.news.Photo 只是一个范围变量,其中包含绘制的图像,其字节由文章中 $scope.uploadFile 函数中的等效字节创建。

    希望对你也有帮助。

    【讨论】:

    • {{news.Photo}} - 但是放什么?文件 [0] 还是什么?谢谢
    • 注意,图像位于浏览器中,而不是在服务器上,直到我点击“保存”
    • 我知道它必须在“保存”之前显示,我更新了我的答案。
    猜你喜欢
    • 2017-01-17
    • 1970-01-01
    • 2016-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    相关资源
    最近更新 更多