简体   繁体   English

返回文件为$ http.post响应

[英]Return file as $http.post response

I want to send some data back to my API and return an .xlsx file as a response, so that the client will be able to download it. 我想将一些数据发送回我的API并返回一个.xlsx文件作为响应,以便客户端能够下载它。 The requirement which makes everything fall apart is that I have to create the .xlsx file as a temporary file. 使一切崩溃的要求是,我必须将.xlsx文件创建为临时文件。 The problem I have been facing is when the file is opened after been downloaded it is completely corrupted. 我一直面临的问题是,在下载文件后打开文件时,它已完全损坏。

I'm using AngularJS and Python Flask 我正在使用AngularJSPython Flask

Here is server side handling : 这是服务器端处理

@app.route('/downloadxlsx', methods=['POST'])
def downloadOrderToExcel():
  try:
    data = request.get_json()
    productsBought = data.pop('products')
    data['datetime'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

    output = io.BytesIO()
    wb = xlsxwriter.Workbook(output, {'in_memory': True})
    ws = wb.add_worksheet(data['fullname'])
    row = col = 0
    for columnName in excelColumnNames():
      ws.write(row, col, columnName)
      col += 1
    col = 0
    row = 1
    for cellValue in data:
      ws.write(row, col, data[cellValue])
      col += 1
    for product in productsBought:
      result = queryForProducts(product)
      for r in result:
        ws.write(row, col, r['categoryname'] + " pack of " + r['pack'])
        row += 1

    output.seek(0)
    wb.close()
    return send_file(output, as_attachment=True, attachment_filename='order.xlsx')
  except Exception as ex:
    print(str(ex))
    return 'False'

Here is request : 这是要求

  vm.downloadExcel = function() {
    this.jsonCustomer = JSON.stringify(vm.customer);
    $http.post('/downloadxlsx', this.jsonCustomer)
    .then(response => {
        let blob = new Blob([response], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        let url = URL.createObjectURL(blob);
        let a = document.createElement('a');
        a.href = url;
        a.target = '_blank';
        a.click();
    })
  }

It seems data is getting corrupted because browser in not able to make the sense of the data (content-type) while reading from blob and writing it in file. 似乎数据已损坏,因为浏览器在从blob读取并将其写入文件时无法理解数据(内容类型)。

looking at you code it seems you are using two step process. 查看您的代码,看来您正在使用两步过程。 1. get user input and provide him download link 2. on click of download link you provide him xlsx file. 1.获得用户输入并为其提供下载链接2.单击下载链接后,您将为其提供xlsx文件。 So why not wait till user click download link and then submit the user input data and respond back with xlxs file directly from server. 因此,为什么不等到用户单击下载链接,然后提交用户输入的数据,并直接从服务器返回xlxs文件,即可。 So content-type will be handled by server only and its browser server interaction without ajax/client intervention in setting content-type. 因此,内容类型将仅由服务器及其浏览器服务器交互处理,而无需ajax /客户端干预来设置内容类型。

Secondly, I see you are simply converting user input into xlsx and responding back. 其次,我看到您只是将用户输入转换为xlsx并进行响应。 So instead of going to server we can develop the xlsx on client side using module like sheetjs 因此,除了使用服务器之外,我们还可以使用sheetjs之类的模块在客户端开发xlsx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM