【问题标题】:What is the equivalent of window.location.href in AngularAngular中window.location.href的等价物是什么
【发布时间】:2018-11-19 11:08:41
【问题描述】:

在我的应用程序中,用户可以从作为 Spring Boot 应用程序的后端以流的形式下载文件,这是后端代码:

@RequestMapping(value = "/download", method = RequestMethod.GET)
public StreamingResponseBody download() throws IOException {

    final InputStream fecFile = new FileInputStream(new File("C:\\file.zip"));;
    return (os) - > {
        readAndWrite(fecFile, os);
    };
}

private void readAndWrite(final InputStream is, OutputStream os) throws IOException {
    byte[] data = new byte[2048];
    int read = 0;
    while ((read = is.read(data)) >= 0) {
        os.write(data, 0, read);
    }
    os.flush();
}

在 Angular 内部,我使用以下内容下载文件:

window.location.href = "http://localhost:8080/download"

哪个工作很好,但是我添加了一个基于访问令牌的身份验证,我无法将令牌添加到 window.location.href,有没有办法以角度来做到这一点,我尝试使用 HttpModule 但它没有下载文件(它没有显示任何响应或错误,即使我的控制器被调用),那么有没有办法使用 jquery 或其他库来实现这一点?

【问题讨论】:

    标签: angular stream


    【解决方案1】:

    您必须创建一个特定的方法(在服务中或直接从组件中,这取决于您,但我更喜欢 SOC 原则,这就是我分开的原因)

    关于服务部分:

    const httpOptions = {
        headers: new HttpHeaders({
          'Key': key
        })
      };
    
      getFile(){
    
        return this.http.get("http://localhost:8080/download", httpOptions )
    
      }
    

    以及稍后在您的组件方面:

     constructor(private myService: MyTestServiceService ) { }
    
    
     downloadFile(data: Response) {
    
        const blob = new Blob([data], { type: 'text/pdf' }); // pdf is an example
        const url= window.URL.createObjectURL(blob);
        window.open(url);
    
    }
    
     myMethodToCallMyService() {
    
       this.myService.getFile()
           .subscribe(
    
             (data) => {
               this.downloadFile(data)
             },
    
            (error) => {
               console.log("Server error");
             }
    
           );
       }
    

    【讨论】:

    • 我已经指定我使用了 HttpModule,但是当它是来自服务器的流时它不起作用。
    • @Svg_af,在浏览器控制台的网络选项卡中,您是否检查过它是否被调用?
    • @AbdenaceurLichiheb,我不知道,但我曾经下载文件(多部分文件),无论如何,你应该尝试使用 REST 客户端(例如:邮递员),如果可行,角度应该如此。跨度>
    • 我尝试使用 curl 它工作正常,仅供参考,这是一个流,而不是我提到的多部分。
    • 同样的事情,没有文件正在下载。
    猜你喜欢
    • 2016-11-02
    • 2014-10-09
    • 2019-12-23
    • 2016-04-06
    • 2017-05-01
    • 2019-03-29
    • 2018-06-17
    • 2016-06-05
    • 1970-01-01
    相关资源
    最近更新 更多