简体   繁体   English

如何下载文件并将文件发送给我的用户?

[英]How do I download and send a file to my user?

I am trying to download a file from a URL and pass it to my user. 我正在尝试从URL下载文件并将其传递给我的用户。

In order for this to work I need to construct a HTTP GET request like this: 为了使其工作,我需要构建一个HTTP GET请求,如下所示:

https://some.service.com/api/pdf?doc_id=99&data[info1]=some+info&data[info2]=more+info

This works fine when I issue it in my browser and I get the correct document including the correct data returned. 当我在浏览器中发出它并且我得到包含返回的正确数据的正确文档时,这可以正常工作。

I want to do the same thing programmatically: 我想以编程方式执行相同的操作:

  • Build the query and request the file via rest-client. 构建查询并通过rest-client请求文件。
  • Serve the file to the user via send_file. 通过send_file将文件提供给用户。

My two problems are: 我的两个问题是:

  1. I am making a mistake in the way I pass my params into rest-client, but I have found no means of checking what the resulting query actually is. 我在将params传递给rest-client的方式上犯了一个错误,但我发现没有办法检查生成的查询实际上是什么。 This makes it hard for me to see what I am doing wrong, since I would just compare the resulting call with my works-in-my-browser call. 这让我很难看到我做错了什么,因为我只是将结果调用与我的浏览器调用进行比较。 All parameters, except for the data[] ones work fine. data[]之外的所有参数都可以正常工作。
  2. I can only serve the correct document (minus the correct data) via send_data , which means I have to specify type and filename again. 我只能通过send_data提供正确的文件(减去正确的数据),这意味着我必须再次指定类型和文件名。 This doesn't make sense since the PDF I am downloading is already all good to go with naming and everything. 这是没有意义的,因为我正在下载的PDF已经很好地与命名和一切。 send_file returns an error. send_file返回错误。

Here's my code: 这是我的代码:

def request_and_send_file
  response = RestClient.get("https://some.service.com/api/pdf", :params => {
    doc_id: 99,
    :data => {
      info1: "some info",
      info2: "more info"}})
  send_data response.body, filename: "hochzeitsfeder.pdf", disposition: "attachment", :content_type => 'application/pdf'
end

Any help is greatly appreciated. 任何帮助是极大的赞赏。

I was able to solve the problem with the parameters. 我能够用参数解决问题。 The parameters work if I make the call like this: 如果我像这样调用这些参数,参数会起作用:

def request_and_send_file
  response = RestClient.get("https://some.service.com/api/pdf", :params => {
    doc_id: 99,
    "data[info1]" => "some info",
    "data[info2]" => "more info"})
  send_data response.body, filename: "customer.pdf", disposition: "attachment", :content_type => 'application/pdf'
end

What I still could not figure out, is why I cannot serve the file I get from the HTTP call via send_file , but have to use send_data . 我仍然无法弄清楚的是,为什么我不能通过send_file从HTTP调用获得的文件,但必须使用send_data

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

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