Serving up bytes over HTTP as file?

agolangf · · 409 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>I feel like this should be really simple, so apologies for the stupid question.</p> <p>I have a service that&#39;s generating PDF data. Rather than first write the data to disk and serve it up using:</p> <pre><code>http.ServeFile(w, f, file) </code></pre> <p>I&#39;d much rather be able to just respond with the data I have in memory, instructing the browser to download it as foo.pdf. Is this possible?</p> <hr/>**评论:**<br/><br/>aminoglycine: <pre><p>Oh, duh. I answered my own question!</p> <pre><code>w.Header().Set(&#34;Content-Disposition&#34;, &#34;attachment; filename=foo.pdf&#34;) w.Header().Set(&#34;Content-Type&#34;, r.Header.Get(&#34;Content-Type&#34;)) w.Write(pdfData) </code></pre></pre>twisted1919: <pre><p>yeah but keep in mind that having a 50MB pdf will eat up that much memory, you need to write it in chunks to avoid huge memory usage.</p></pre>nemith: <pre><p>You can still set the headers and then use ServeFile as well. It is slightly better than io.Copy </p></pre>dchapes: <pre><p>See <a href="https://golang.org/pkg/net/http#ServeContent"><code>http.ServeContent</code></a>:</p> <blockquote> <p>The main benefit of ServeContent over <code>io.Copy</code> [direct <code>Write</code> call in your case] is that it handles <code>Range</code> requests properly, sets the MIME type, and handles <code>If-Modified-Since</code> requests.</p> </blockquote> <p>Assuming your <code>pdfData</code> variable is a <code>[]byte</code> that you know was generated at <code>modtime time.Time</code> you&#39;d just do:</p> <pre><code>http.ServeContent(w, r, &#34;foo.pdf&#34;, modtime, bytes.NewReader(pdfData)) </code></pre></pre>aminoglycine: <pre><p>This seems like the best solution. Thanks!</p></pre>gohacker: <pre><p><code>w.Header().Set(&#34;Content-Type&#34;, r.Header.Get(&#34;Content-Type&#34;))</code></p> <p>Use <code>&#34;application/pdf&#34;</code> instead of setting content type from the request.</p></pre>aminoglycine: <pre><p>good catch, thank you</p></pre>twisted1919: <pre><p>This should be possible if you set proper download headers and then you simply write the contents of the pdf in w as they come, from memory.</p> <p>This should help more: <a href="http://stackoverflow.com/questions/24116147/golang-how-to-download-file-in-browser-from-golang-server" rel="nofollow">http://stackoverflow.com/questions/24116147/golang-how-to-download-file-in-browser-from-golang-server</a></p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

409 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传