Created
April 21, 2021 14:46
-
-
Save misaka00251/07cc9d5b796358276d51c529b42a7055 to your computer and use it in GitHub Desktop.
This is a file upload demo for music.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Golang testing</title> | |
</head> | |
<body> | |
<p>Please upload your favourite music.</p> | |
<br> | |
<form enctype="multipart/form-data" action="/upload" method="post"> | |
<input type="file" name="uploadFile"> | |
<input type="submit" value="upload"> | |
</form> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"fmt" | |
"github.com/dhowden/tag" | |
"github.com/google/uuid" | |
"html/template" | |
"image" | |
"image/jpeg" | |
"io" | |
"log" | |
"net/http" | |
"os" | |
"path" | |
"path/filepath" | |
"time" | |
) | |
type metadata struct { | |
Format string `json:"format"` | |
Title string `json:"Title"` | |
Album string `json:"Album"` | |
Artist string `json:"Artist"` | |
Genre string `json:"Genre"` | |
Cover string `json:"Cover"` | |
Created time.Time `json:"Created"` | |
} | |
func uploadHandler(w http.ResponseWriter, r *http.Request) { | |
switch r.Method { | |
case "GET": | |
t := template.Must(template.ParseFiles("dist/index.html.gohtml")) | |
err := t.Execute(w, nil) | |
if err != nil { | |
log.Fatal(err) | |
} | |
case "POST": | |
uploadFile(w, r) | |
} | |
} | |
func uploadFile(w http.ResponseWriter, r *http.Request) { | |
// Max 10 MB | |
r.ParseMultipartForm(10 << 20) | |
file, handler, err := r.FormFile("uploadFile") | |
uploadTime := time.Now() | |
if err != nil { | |
fmt.Println("Error retrieving the File") | |
fmt.Println(err) | |
return | |
} | |
defer file.Close() | |
fmt.Printf("Uploaded File: %+v\n", handler.Filename) | |
fmt.Printf("File Size: %+v\n", handler.Size) | |
fmt.Printf("MIME Header: %+v\n", handler.Header) | |
os.Mkdir("upload", 0755) | |
//if err := os.MkdirAll(filepath.Dir("upload"), 0770); err != nil { | |
// log.Fatal(err) | |
//} | |
currentDirectory, _ := os.Getwd() | |
fileNameUUID := uuid.New().String() | |
// Note: upload file rename as UUID.mp3 | |
filePath, _ := filepath.Abs(currentDirectory + "/upload/" + fileNameUUID + path.Ext(handler.Filename)) | |
fmt.Println(filePath) | |
dst, createErr := os.Create(filePath) | |
if createErr != nil { | |
http.Error(w, createErr.Error(), http.StatusInternalServerError) | |
return | |
} | |
if _, err = io.Copy(dst, file); err != nil { | |
http.Error(w, err.Error(), http.StatusInternalServerError) | |
return | |
} | |
dst.Close() | |
// Write metadata into JSON file. | |
// Get metadata from file | |
opendst, _ := os.Open(filePath) | |
m, detectErr := tag.ReadFrom(opendst) | |
if detectErr != nil { | |
fmt.Println("Error when reading from music file.") | |
log.Fatal(err) | |
} | |
// Read cover from file | |
filecover := m.Picture().Data | |
// Decode []byte image for compression | |
img, _, _ := image.Decode(bytes.NewReader(filecover)) | |
// New picture to write | |
filePath, _ = filepath.Abs(currentDirectory + "/upload/" + fileNameUUID + ".jpg") | |
nimg, _ := os.Create(filePath) | |
opt := jpeg.Options{ | |
Quality: 75, | |
} | |
err = jpeg.Encode(nimg, img, &opt) | |
defer nimg.Close() | |
metadataFromFile := metadata{ | |
Format: string(m.Format()), | |
Title: m.Title(), | |
Album: m.Album(), | |
Artist: m.Artist(), | |
Genre: m.Genre(), | |
// Temp | |
Cover: fileNameUUID + ".jpg", | |
Created: uploadTime, | |
} | |
defer opendst.Close() | |
// Create json | |
var jsonData []byte | |
jsonData, err = json.MarshalIndent(metadataFromFile, "", " ") | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(string(jsonData)) | |
// Create json file | |
filePath, _ = filepath.Abs(currentDirectory + "/upload/" + fileNameUUID + ".json") | |
dst2, createErr2 := os.Create(filePath) | |
_ = os.WriteFile(filePath, jsonData, 0644) | |
if createErr2 != nil { | |
http.Error(w, createErr2.Error(), http.StatusInternalServerError) | |
return | |
} | |
defer dst2.Close() | |
fmt.Fprintf(w, "Successfully Uploaded File\n") | |
} | |
func main() { | |
addr := "localhost:8089" | |
fmt.Printf("HTTP Server starting at http://%s...\n", addr) | |
http.HandleFunc("/upload", uploadHandler) | |
if http.ListenAndServe(addr, nil) != nil { | |
panic("shutdown") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment