Skip to content

Instantly share code, notes, and snippets.

@tabula-rasa
Created November 20, 2015 19:25
Show Gist options
  • Save tabula-rasa/0f1d55903e0cb0a3f221 to your computer and use it in GitHub Desktop.
Save tabula-rasa/0f1d55903e0cb0a3f221 to your computer and use it in GitHub Desktop.
Golang handler for Ckeditor image upload
package controllers
import (
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
)
//CkUpload handles /ckupload route
func CkUpload(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
err := r.ParseMultipartForm(32 << 20)
if err != nil {
log.Printf("ERROR: %s\n", err)
http.Error(w, err.Error(), 500)
return
}
mpartFile, mpartHeader, err := r.FormFile("upload")
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer mpartFile.Close()
uri, err := saveFile(mpartHeader, mpartFile)
if err != nil {
log.Println(err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
CKEdFunc := r.FormValue("CKEditorFuncNum")
fmt.Fprintln(w, "<script>window.parent.CKEDITOR.tools.callFunction("+CKEdFunc+", \""+uri+"\");</script>")
} else {
err := fmt.Errorf("Method %q not allowed", r.Method)
log.Printf("ERROR: %s\n", err)
http.Error(w, err.Error(), 405)
}
}
//saveFile saves file to disc and returns its relative uri
func saveFile(fh *multipart.FileHeader, f multipart.File) (string, error) {
fileExt := filepath.Ext(fh.Filename)
newName := fmt.Sprint(time.Now().Unix()) + fileExt //unique file name based on timestamp. You can keep original name and ignore duplicates
uri := "/public/uploads/" + newName
fullName := filepath.Join('/path/to/uploads/dir', newName)
file, err := os.OpenFile(fullName, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return "", err
}
defer file.Close()
_, err = io.Copy(file, f)
if err != nil {
return "", err
}
return uri, nil
}
@TuralAsgar
Copy link

in line 53 it must be double quotes. Thank you for your gist!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment