LoginSignup
3
0

More than 5 years have passed since last update.

レスポンスボディから得られる画像を保存せずに、zip してブラウザでダウンロードさせるサンプル

Posted at

適当な画像URLから、その画像をブラウザでダウンロードさせるサンプルです。

ぼくは最初、画像URLから取得した画像を "適当なファイルとして保存して圧縮" という流れでやっていましたが。この "保存して" という処理を省きたかったのです。省いたサンプルが以下になります。

(もっといい方法とかあるのかなぁ..

server.go
package main

import (
    "archive/zip"
    "io/ioutil"
    "net/http"
    "html/template"
)

func indexHandler(w http.ResponseWriter, r *http.Request) {
    t, _ := template.ParseFiles("index.html")
    t.Execute(w, nil)
}

func downloadHandler(w http.ResponseWriter, r *http.Request) {
    imageURL := "適当な画像URL"
    res, _ := http.Get(imageURL)
    data, _ := ioutil.ReadAll(res.Body)
    defer res.Body.Close()

    zw := zip.NewWriter(w)
    defer zw.Close()

    writer, _ := zw.Create("create.png")
    w.Header().Set("Content-Disposition", "attachment; filename=tmp.zip")
    w.Header().Set("Content-Type", "application/zip")
    writer.Write(data)
}

func main() {
    http.HandleFunc("/", indexHandler)
    http.HandleFunc("/download", downloadHandler)
    http.ListenAndServe(":8000", nil)
}
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
  tmp
  <form method="post" action="/download">
    <input type="submit" value="Download Image">
  </form>
</body>
</html>
3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0