Browse Source

recieve an image and stores it to a file

master
arnaucode 7 years ago
parent
commit
5df6ca9a94
1 changed files with 8 additions and 22 deletions
  1. +8
    -22
      handlers.go

+ 8
- 22
handlers.go

@ -1,9 +1,7 @@
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
@ -21,29 +19,17 @@ func ImageShow(w http.ResponseWriter, r *http.Request) {
}
func NewImage(w http.ResponseWriter, r *http.Request) {
var img ImageModel
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
file, handler, err := r.FormFile("file")
if err != nil {
panic(err)
fmt.Println(err)
}
if err := r.Body.Close(); err != nil {
panic(err)
data, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(body))
if err := json.Unmarshal(body, &img); err != nil {
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(422) // unprocessable entity
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
err = ioutil.WriteFile(handler.Filename, data, 0777)
if err != nil {
fmt.Println(err)
}
img.File = body
fmt.Println(img)
fmt.Println(img.File)
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(img.File); err != nil {
panic(err)
}
}

Loading…
Cancel
Save