File Uploading feature by tfasano1
This commit is contained in:
@ -61,6 +61,13 @@ func (getController *GetController) ShowLogin(w http.ResponseWriter, r *http.Req
|
||||
templating.RenderTemplate(getController.App, w, "templates/pages/login.html", data)
|
||||
}
|
||||
|
||||
func (getController *GetController) ShowFile(w http.ResponseWriter, r *http.Request) {
|
||||
// GET /uploads?name=file.jpg
|
||||
// will serve file.jpg
|
||||
name := r.URL.Query().Get("name")
|
||||
http.ServeFile(w, r, getController.App.Config.Upload.BaseName+name)
|
||||
}
|
||||
|
||||
func (getController *GetController) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
models.LogoutUser(getController.App, w, r)
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
|
@ -4,8 +4,10 @@ import (
|
||||
"GoWeb/app"
|
||||
"GoWeb/models"
|
||||
"GoWeb/security"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
@ -69,3 +71,46 @@ func (postController *PostController) Register(w http.ResponseWriter, r *http.Re
|
||||
|
||||
http.Redirect(w, r, "/login", http.StatusFound)
|
||||
}
|
||||
|
||||
func (postController *PostController) FileUpload(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
max := postController.App.Config.Upload.MaxSize
|
||||
r.ParseMultipartForm(max)
|
||||
|
||||
// FormFile returns the first file for the given key `file`
|
||||
// it also returns the FileHeader so we can get the Filename,
|
||||
// the Header and the size of the file
|
||||
file, handler, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
log.Println("Error Retrieving the File")
|
||||
log.Println(err)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
if handler.Size > max {
|
||||
log.Println("User tried uploading a file which is too large.")
|
||||
http.Redirect(w, r, "/", http.StatusRequestHeaderFieldsTooLarge)
|
||||
return
|
||||
}
|
||||
|
||||
// Create a temporary file within upload directory
|
||||
tempFile, err := os.Create(postController.App.Config.Upload.BaseName + handler.Filename)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
http.Redirect(w, r, "/", http.StatusNotAcceptable)
|
||||
}
|
||||
defer tempFile.Close()
|
||||
|
||||
// read all of the contents of our uploaded file into a
|
||||
// byte array
|
||||
fileBytes, err := ioutil.ReadAll(file)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
// write this byte array to our temporary file
|
||||
tempFile.Write(fileBytes)
|
||||
// return that we have successfully uploaded our file!
|
||||
|
||||
http.Redirect(w, r, "/", http.StatusFound)
|
||||
}
|
||||
|
Reference in New Issue
Block a user