【问题标题】:How to output to a file and get the specific header file in cURL?如何输出到文件并获取 cURL 中的特定头文件?
【发布时间】:2017-01-03 14:10:16
【问题描述】:

我有一个要使用 cURL 下载的文件链接,我需要将此文件输出到某个临时文件,还需要获取特定的标头值。

例子:

Link: http://my.download.url<br>
Output to: /tmp/my-downloaded-file<br>
Header(Content-Length or whatever): abc123

【问题讨论】:

  • 提供要从中提取内容的准确输出
  • @Inian 我想将输出复制到一个名为 content-disposition 的文件(我将提供的路径)中。
  • 很公平!写完之后你想做什么?举个例子
  • @Inian 我将获取名称并在我的产品中运行文件。我需要该名称,因为它作为参数传递给某个函数。
  • 我在这里没有看到问题,您可以通过curl -s &lt;url-here&gt; &gt; &lt;name-of-your-file&gt; 来执行此操作吗?你打算这样做吗?

标签: linux unix curl


【解决方案1】:

那么,文件名取决于标头的值?

据我所知,cURL 不允许您在一个流上获取标头(例如标准输出),而在另一个流上获取正文。您需要做的是将所有这些放在一起并解析出来,或者执行两个调用。下面是两种调用方式:

# URL and the header you want
url="http://www.example.com"
hdr="Content-Length"

# get the value of the header (this does not download the body)
headerValue=$(curl -sI "$url" | grep -i "^$hdr:" | cut -f2 -d: | sed 's/^[ \r\n\t]*//;s/[ \r\n\t]*$//')

# create a file name from that header value
fileName="/tmp/download-$headerValue"

# download the body into that file
curl -so "$fileName" "$url"

【讨论】:

  • 第一个调用执行HEAD,它下载标头。第二个调用执行GET,它下载标题正文。
  • Oww 得到它,所以它没有下载 2 次。谢谢!
猜你喜欢
  • 1970-01-01
  • 2012-11-23
  • 2019-08-17
  • 1970-01-01
  • 1970-01-01
  • 2019-10-14
  • 2010-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多