upload.go 1.23 KB
Newer Older
1
2
3
4
5
6
7
package main

import (
	"bytes"
	"crypto/sha256"
	"encoding/json"
	"fmt"
Max Reeves's avatar
Max Reeves committed
8
9
10
	"image"
	_ "image/jpeg"
	_ "image/png"
11
	"io/ioutil"
Max Reeves's avatar
Max Reeves committed
12
	"log"
13
	"net/http"
Max Reeves's avatar
Max Reeves committed
14
	"os"
15
16
17
18
	"path"
	"path/filepath"
)

StreatCodes's avatar
StreatCodes committed
19
20
21
//ResponseURL helper struct to send return URLs to the client
//TODO change to hash, and fix frontend
type ResponseURL struct {
22
23
24
	URL string `json:"url"`
}

Max Reeves's avatar
Max Reeves committed
25
26
27
28
29
30
31
32
33
34
35
36
37
func getImageDimension(imagePath string) (int, int) {
	file, err := os.Open(imagePath)
	if err != nil {
		log.Println(err)
	}

	image, _, err := image.DecodeConfig(file)
	if err != nil {
		log.Println(imagePath, err)
	}
	return image.Width, image.Height
}

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
func handleUpload(w http.ResponseWriter, r *http.Request) {
	extension := filepath.Ext(r.Header.Get("filename"))

	buf := new(bytes.Buffer)
	buf.ReadFrom(r.Body)
	contents := buf.Bytes()

	h := sha256.New()
	h.Write(contents)
	hash := fmt.Sprintf("%x", h.Sum(nil)[0:16])

	filepath := path.Join("dashboards-data", hash+extension)
	err := ioutil.WriteFile(filepath, contents, 0655)
	if err != nil {
		fmt.Printf("error writing to file %s\n", err)
		http.Error(w, "error writing to file %s\n", http.StatusInternalServerError)
		return
	}

	fmt.Printf("Created file %s\n", filepath)
	enc := json.NewEncoder(w)
59
	enc.Encode(ResponseURL{URL: path.Join("/", filepath)})
60
}