file_upload/image_upload.go

68 lines
1.3 KiB
Go

package main
import (
"bytes"
"fmt"
"image"
_ "image/gif"
"image/jpeg"
_ "image/png"
"io/ioutil"
"log"
"net/http"
"os"
exifremove "github.com/scottleedavis/go-exif-remove"
)
func uploadhandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
if err := r.ParseMultipartForm(32 << 20); err != nil {
http.Error(w, "File is too big", http.StatusBadRequest)
fmt.Println(err)
return
}
file, handler, err := r.FormFile("myFile")
if err != nil {
http.Error(w, "Cannot retrieve file", http.StatusNotFound)
fmt.Println(err)
return
}
defer file.Close()
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println(err)
}
noExifBytes, err := exifremove.Remove(fileBytes)
if err != nil {
fmt.Println(err)
return
}
img, _, err := image.Decode(bytes.NewReader(noExifBytes))
if err != nil {
fmt.Println(err)
return
}
out, err := os.Create("./files/" + handler.Filename)
if err != nil {
fmt.Println(err)
return
} else {
fmt.Print("Successfully uploaded: " + handler.Filename + "\n")
}
defer out.Close()
var opts jpeg.Options
opts.Quality = 100
err = jpeg.Encode(out, img, &opts)
if err != nil {
fmt.Println(err)
return
}
}
func main() {
http.HandleFunc("/upload", uploadhandler)
log.Fatal(http.ListenAndServe(":8081", nil))
}