【问题标题】:get image file object from url从 url 获取图像文件对象
【发布时间】:2016-06-22 15:27:01
【问题描述】:

我正在制作一个 django-angularjs webapp。 有一个供用户上传文件的选项。

我想为用户提供一些示例图片以供上传。
因此,就像示例图像将由服务器发送到客户端,如果客户端选择它们作为新鲜上传,则再次发送回服务器。

angularjs 指令:

angular.module('users').directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
    var model = $parse(attrs.fileModel);
    var modelSetter = model.assign;

    element.bind('change', function(){
        scope.$apply(function(){
            modelSetter(scope, element[0].files[0]);
        });
    });
}
};
}]);

我的html:

<input type="file" file-model="myFile"/><br><br>
<button ng-click="uploadFile()">Upload</button>

angular-js 控制器:

$scope.uploadFile = function(){

    var file = $scope.myFile;
    var uploadUrl = "/multer";
    var fd = new FormData();
    fd.append('file', file);

    $http.post(uploadUrl,fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(){
      console.log("success!!");
    })
    .error(function(){
      console.log("error!!");
    });
};

使用上面的代码,用户可以从他们的电脑中选择图像并上传它们。

现在,如果我们有服务器发送的示例图像的 url。 如何编码角度控制器以从这些 url 获取文件对象的图像?
$scope.myFile=getImageFileObjectFromUrl(url) ??

感谢帮助

【问题讨论】:

    标签: html angularjs django angularjs-directive


    【解决方案1】:

    也有帮助

      $http.get(url.path, {responseType: "blob"}).then((res) => {
       let fileUrl = (window.URL || window.webkitURL).createObjectURL(res.data);
       resolve({file: fileUrl, type: url.type, name: url.name});
      });
    

    【讨论】:

      【解决方案2】:

      将图像从给定的 url 转换为文件对象:

      $http.get(url,{responseType: "blob"}).success((data) => {
        var file = new File([data], "sample.jpg");
        $scope.sampleFile=file;
      });
      

      【讨论】:

        【解决方案3】:
        $http.get("image_url", {responseType: "arraybuffer"}).success((data) => {
            fd.append('file', data);
        });
        

        这是一个普遍的想法,当您获取图像 url 时,只需将请求作为 arraybuffer 到 URL,然后您只需将 blob 对象传递给您的 formdata。

        【讨论】:

        • 不工作...数据总是空数组缓冲区。虽然我在删除响应类型时可以看到 jpeg 数据。
        • 你使用哪个版本的 Angular ?
        • 您将不得不使用 XHR2 来使 arraybuffer 工作,所以也许只使用原始 XMLHttpRequest 2 而不是 angular 的 $http。
        • 嗨,有什么想法可以将此图像显示到 HTML 端吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-31
        • 2018-01-09
        • 2015-10-02
        • 2020-03-24
        • 1970-01-01
        • 2012-01-09
        相关资源
        最近更新 更多