Last active
June 1, 2018 20:29
-
-
Save tabula-rasa/dc0a9e91088c4e387d871f0eade64fa4 to your computer and use it in GitHub Desktop.
The go handler (server-side script) for standard CkEditor 5 image upload
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
$(document).ready(function () { | |
ClassicEditor | |
.create(document.querySelector('#ck-content'), { | |
ckfinder: { | |
uploadUrl: '/upload' | |
}, | |
}) | |
.catch(error => { | |
console.error(error); | |
}); | |
}); |
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 controllers | |
import ( | |
"io" | |
"fmt" | |
"mime/multipart" | |
"net/http" | |
"os" | |
"path/filepath" | |
"time" | |
"github.com/gin-gonic/gin" | |
) | |
//UploadPost handles POST /upload route | |
func UploadPost(c *gin.Context) { | |
err := c.Request.ParseMultipartForm(32 << 20) // ~32MB | |
if err != nil { | |
c.JSON(http.StatusBadRequest, "") | |
return | |
} | |
mpartFile, mpartHeader, err := c.Request.FormFile("upload") | |
if err != nil { | |
c.String(400, err.Error()) | |
return | |
} | |
defer mpartFile.Close() | |
uri, err := saveFile(mpartHeader, mpartFile) | |
if err != nil { | |
c.JSON(http.StatusInternalServerError, err.Error()) | |
return | |
} | |
c.JSON(http.StatusOK, gin.H{"uploaded": true, "url": uri}) | |
} | |
//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 ;D | |
uri := "/public/uploads/" + newName | |
fullName := filepath.Join("public", "uploads", 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment