Fieldnotes app backend

tiff_optimizer.go 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "os"
  9. "os/exec"
  10. "path"
  11. "github.com/go-chi/chi"
  12. "github.com/pborman/uuid"
  13. )
  14. func showTiffOptimizerPage(w http.ResponseWriter, r *http.Request) {
  15. if err := xt.ExecuteTemplate(w, "tiff_optimizer.html.tmpl", nil); err != nil {
  16. panic(err)
  17. }
  18. }
  19. func uploadImage(w http.ResponseWriter, r *http.Request) {
  20. if err := r.ParseForm(); err != nil {
  21. panic(err)
  22. }
  23. file, _, err := r.FormFile("tiffImage")
  24. if err != nil {
  25. panic(err)
  26. }
  27. sourceFile, err := ioutil.TempFile("", "tiff-optimizer")
  28. if err != nil {
  29. panic(err)
  30. }
  31. defer os.Remove(sourceFile.Name())
  32. if _, err := io.Copy(sourceFile, file); err != nil {
  33. panic(err)
  34. }
  35. resultID := uuid.New()
  36. destFile := path.Join(tiffDir, resultID+".tif")
  37. cmd := exec.CommandContext(
  38. r.Context(),
  39. "gdal_translate",
  40. "-co", "COMPRESS=LZW",
  41. sourceFile.Name(),
  42. destFile,
  43. )
  44. cmd.Stdout = os.Stdout
  45. cmd.Stderr = os.Stderr
  46. log.Printf("executing '%s'", cmd.Args)
  47. if err := cmd.Run(); err != nil {
  48. panic(err)
  49. }
  50. url := fmt.Sprintf("/tiff-optimizer/results/%s", resultID)
  51. http.Redirect(w, r, url, http.StatusSeeOther)
  52. }
  53. func downloadResult(w http.ResponseWriter, r *http.Request) {
  54. resultID := chi.URLParam(r, "ID")
  55. if resultID == "" {
  56. http.Redirect(w, r, "/tiff-optimizer", http.StatusSeeOther)
  57. return
  58. }
  59. filePath := path.Join(tiffDir, resultID+".tif")
  60. if _, err := os.Stat(filePath); err != nil {
  61. if os.IsNotExist(err) {
  62. http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
  63. return
  64. }
  65. panic(err)
  66. }
  67. w.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s.tif\"", resultID))
  68. http.ServeFile(w, r, filePath)
  69. }