首页 文章

带有angular2的Nativescript,如何从受保护的服务器中检索图像

提问于
浏览
0

我使用 nativescriptangular2 到一个简单的图像库,但图像在受保护的服务器..在Web应用程序中,这是由会话cookie解决..但在这里我必须实现一个令牌身份验证 .

我正在通过以下方式下载图片:

get(url: string) {
      let headers = new Headers();
      headers.append("Authorization", "Token " + Config.token);
      return this.http.get(this.base_url+url, { headers: headers, })
  }

在我的组件中:

this.mediaService.get(obj.url_tn)
                .subscribe(data=> 

                {
                     let file:Blob = new Blob([data.arrayBuffer()]);
                     console.dump(data);
                     let urlFile =  URL.createObjectURL(file );
                     this.photos.push(urlFile) ;

                })

但这给了我一个错误:

错误:错误:0:0引起:Blob未定义

我不知道为什么将 Headers 添加到 img 太难了,如何以简单的方式存档?

谢谢

2 回答

  • 0

    NativeScript的 http 模块有一个名为 getImage(...) 的函数 .

    我自己没有尝试过,但我认为您应该可以使用它来加载私人服务中的图像:

    http://docs.nativescript.org/api-reference/modules/http.html#getimage

    注意: getImage(...) 采用 URL -string或 HttpRequestOptions -object .

    我建议为它创建一个管道,就像我为image-cache写的那个:https://gist.github.com/m-abs/9e640e5805a21a842d55e02b291147c5

  • 0

    这是如何,但不是在nativescript / angular2方式,这是一个后端,使用django ..

    import base64
    import mimetypes
    from django.http import FileResponse, HttpResponse
    
        def download(request):
    
            """
            your way to get your file and original_filename
            """
    
            type, encoding = mimetypes.guess_type(original_filename)
            if type is None:
                type = 'application/octet-stream'
    
            if request.GET.get('base64'):
                response =  HttpResponse("data:"+type+";base64,"+base64.b64encode(fobject.read()))
            else:
                response =  FileResponse(fobject)
                response['Content-Type'] = type
                response['Content-Length'] = str(os.stat(file_path).st_size)
                if encoding is not None:
                    response['Content-Encoding'] = encoding
            """
            ETC ETC ETC
            """
            return response
    

相关问题