【问题标题】:AngularJS file upload display image in drag and dropAngularJS文件上传拖拽显示图片
【发布时间】:2015-04-17 15:28:09
【问题描述】:

每当有人使用 angular js file upload 将图像拖放到 Dropbox 中时,我都会尝试使图像可见 我也在 SO 上查看了at this post,但无法使其工作。

我尝试了各种方法,例如显示 blob、显示文件,但在将图像拖放到该区域后,我无法显示图像。

HTML:

<div ng-file-drop ng-model="files" ng-file-change="placeImage()"
drag-over-class="dragover" ng-multiple="false" class="dropbox" allow-dir="true"
accept=".jpg,.png,.pdf">Drop photo here!</div>

AngularJS:

$scope.placeImage = function () {
    var files = $scope.files;
        if (files && files.length) {
            for (var i = 0; i < files.length; i++) {
                ('.dropper').html(files[i]); //does not work: obvious desperate move
                ('.dropper').html(files[i].__proto__.__proto__); //Doesn't work (even tried 64base)
            }
        }
}

图片放入Dropbox后如何显示?

更新

以下也不起作用:

 $("<img />").attr("src", files[i]).appendTo(".dropper");

 $("<img />").attr("src", files[i].__proto__.__proto__).appendTo(".dropper");

然后出现以下错误:

  http://localhost:8080/project/[object%20Object] 404 (Not Found)

更新 2:

使用以下方法修复:

$scope.placeImage = function () {
        var ctx = document.getElementById('canvas').getContext('2d');
        var url = URL.createObjectURL($scope.files[0]);
        var img = new Image();
        img.onload = function() {
            ctx.drawImage(img, 20, 20);    
        }
        img.src = url;
}

【问题讨论】:

    标签: angularjs angular-file-upload


    【解决方案1】:

    文件不是 HTML 元素。您必须将文件分配为 img 标签的 src。

    $("<img />").attr("src", files[i]).appendTo(".dropper");
    

    我认为上面的单行代码可以与 angular 的内置 jQuery lite 一起使用,但它可能需要 jQuery。它至少应该让你知道你需要做什么。

    【讨论】:

    • +1 好点谢谢。不幸的是,如果我查看控制台,我仍然会收到错误消息。 (请参阅更新后的帖子)
    • 我不熟悉 ng-file-drop 指令,但它看起来像是将文件数据包装在文件对象中并在上传之前访问它,您必须使用 FileReader api ,根据您在上面链接到的答案。
    • 我设法修复了它(见更新 2)。即使我没有完全使用您的上述方式,但我感谢您的回答和参考,我认为它甚至比我的方式更好,稍后会看看。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 2012-06-08
    相关资源
    最近更新 更多