代码之家  ›  专栏  ›  技术社区  ›  Venomoustoad

如何从Angular8下载文件?

  •  0
  • Venomoustoad  · 技术社区  · 6 年前

    我正在尝试使用文件保护程序包将文件从服务器保存到桌面。我使用的后端是rails。我在呈现正确格式时遇到问题。

    我的组件:

    import { saveAs } from 'file-saver';
    
    this.http.post(myApiUrl, {responseType: 'blob'}).subscribe(
      blob => saveAs(blob, 'temp.txt')
    )
    

    我的Rails应用程序

    def myApi
      #generate results (this is txt content which is correctly loading)
      send_data results, :type => :json
    end
    

    我看到数据是从服务器发送的。我还可以在控制台的error.text中看到文件内容。我的js控制台上出现以下错误:

    SyntaxError: Unexpected token N in JSON at position
    

    看起来格式不匹配,对吧?我错过了什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Adrita Sharma    6 年前

    这样试试:

    this.http.post(myApiUrl,null, {responseType: 'blob'}).subscribe(
      blob => saveAs(blob, 'temp.txt')
    )
    
    推荐文章