-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
cf0b830
commit 4c21883
Showing
5 changed files
with
136 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
photos/* |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
module Lepus | ||
|
||
go 1.12 | ||
|
||
require github.com/go-chi/chi v4.0.2+incompatible |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
github.com/go-chi/chi v4.0.2+incompatible h1:maB6vn6FqCxrpz4FqWdh4+lwpyZIQS7YEAUcHlgXVRs= | ||
github.com/go-chi/chi v4.0.2+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
// copyright Jusong Chen | ||
|
||
package main | ||
|
||
import ( | ||
"crypto/rand" | ||
"fmt" | ||
"io/ioutil" | ||
"log" | ||
"net/http" | ||
"os" | ||
"path/filepath" | ||
|
||
"github.com/go-chi/chi" | ||
) | ||
|
||
const maxUploadSize = 20 * 1024 * 1024 // 20 mb | ||
|
||
const dirForPhotos = "./photos" | ||
|
||
func uploadFileHandler() http.HandlerFunc { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
// validate file size | ||
r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize) | ||
if err := r.ParseMultipartForm(maxUploadSize); err != nil { | ||
renderError(w, "FILE_TOO_BIG", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
// parse and validate file and post parameters | ||
fileType := r.PostFormValue("type") | ||
file, _, err := r.FormFile("uploadFile") | ||
if err != nil { | ||
renderError(w, "INVALID_FILE", http.StatusBadRequest) | ||
return | ||
} | ||
defer file.Close() | ||
fileBytes, err := ioutil.ReadAll(file) | ||
if err != nil { | ||
renderError(w, "INVALID_FILE", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
// check file type, detectcontenttype only needs the first 512 bytes | ||
filetype := http.DetectContentType(fileBytes) | ||
switch filetype { | ||
case "image/jpeg", "image/jpg": | ||
case "image/gif", "image/png": | ||
case "application/pdf": | ||
break | ||
default: | ||
renderError(w, "INVALID_FILE_TYPE", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
fileName := randToken(12) | ||
// fileEndings, err := mime.ExtensionsByType(fileType) | ||
fileEndings := []string{".jpg"} | ||
|
||
if err != nil { | ||
renderError(w, "CANT_READ_FILE_TYPE", http.StatusInternalServerError) | ||
return | ||
} | ||
newPath := filepath.Join(dirForPhotos, fileName+fileEndings[0]) | ||
fmt.Printf("FileType: %s, File: %s\n", fileType, newPath) | ||
|
||
// write file | ||
newFile, err := os.Create(newPath) | ||
if err != nil { | ||
renderError(w, "CANT_WRITE_FILE", http.StatusInternalServerError) | ||
return | ||
} | ||
defer newFile.Close() // idempotent, okay to call twice | ||
if _, err := newFile.Write(fileBytes); err != nil || newFile.Close() != nil { | ||
renderError(w, "CANT_WRITE_FILE", http.StatusInternalServerError) | ||
return | ||
} | ||
w.Write([]byte("SUCCESS")) | ||
}) | ||
} | ||
|
||
func renderError(w http.ResponseWriter, message string, statusCode int) { | ||
w.WriteHeader(http.StatusBadRequest) | ||
w.Write([]byte(message)) | ||
} | ||
|
||
func randToken(len int) string { | ||
b := make([]byte, len) | ||
rand.Read(b) | ||
return fmt.Sprintf("%x", b) | ||
} | ||
|
||
func main() { | ||
// create the director for uploaded files | ||
path := dirForPhotos | ||
if _, err := os.Stat(path); os.IsNotExist(err) { | ||
err1 := os.Mkdir(path, 0700) | ||
if err1 != nil { | ||
fmt.Fprintf(os.Stderr, "Create dir '%s' failed:%s", path, err1) | ||
os.Exit(1) | ||
} | ||
} | ||
|
||
r := chi.NewRouter() | ||
|
||
r.Get("/", http.FileServer(http.Dir("./public")).ServeHTTP) | ||
|
||
r.Post("/upload", uploadFileHandler()) | ||
log.Print("Lepus started on localhost:8080 ") | ||
log.Fatal(http.ListenAndServe(":8080", r)) | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
<!doctype html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="utf-8"> | ||
<title>Single file upload</title> | ||
</head> | ||
<body> | ||
<h1>Upload single file with fields</h1> | ||
|
||
<form action="/upload" method="post" enctype="multipart/form-data"> | ||
Name: <input type="text" name="name"><br> | ||
<!-- Email: <input type="email" name="email"><br> --> | ||
Files: <input type="file" name="uploadFile"><br><br> | ||
<input type="submit" value="Submit"> | ||
</form> | ||
</body> | ||
</html> |