API drop file upload.

This commit is contained in:
Miroslav Šedivý 2021-01-06 20:03:41 +01:00
parent a104fc0525
commit 3e52b264ba

View File

@ -1,23 +1,77 @@
package room package room
import ( import (
"os"
"io"
"io/ioutil"
"path"
"strconv"
"net/http" "net/http"
"demodesk/neko/internal/utils" "demodesk/neko/internal/utils"
) )
type DropPayload struct { const (
X int `json:"x"` // Maximum upload of 32 MB files.
Y int `json:"y"` MAX_UPLOAD_SIZE = 32 << 20
Files []string `json:"files"` )
}
func (h *RoomHandler) dropFiles(w http.ResponseWriter, r *http.Request) { func (h *RoomHandler) dropFiles(w http.ResponseWriter, r *http.Request) {
data := &DropPayload{} r.ParseMultipartForm(MAX_UPLOAD_SIZE)
if !utils.HttpJsonRequest(w, r, data) {
X, err := strconv.Atoi(r.FormValue("x"))
if err != nil {
utils.HttpBadRequest(w, err)
return return
} }
h.desktop.DropFiles(data.X, data.Y, data.Files) Y, err := strconv.Atoi(r.FormValue("y"))
if err != nil {
utils.HttpBadRequest(w, err)
return
}
req_files := r.MultipartForm.File["files"]
if len(req_files) == 0 {
utils.HttpBadRequest(w, "No file received.")
return
}
dir, err := ioutil.TempDir("", "neko-drop-*")
if err != nil {
utils.HttpInternalServerError(w, err)
return
}
files := []string{}
for _, req_file := range req_files {
path := path.Join(dir, req_file.Filename)
srcFile, err := req_file.Open()
if err != nil {
utils.HttpInternalServerError(w, err)
return
}
defer srcFile.Close()
dstFile, err := os.OpenFile(path, os.O_APPEND | os.O_CREATE | os.O_WRONLY, 0644)
if err != nil {
utils.HttpInternalServerError(w, err)
return
}
defer dstFile.Close()
_, err = io.Copy(dstFile, srcFile)
if err != nil {
utils.HttpInternalServerError(w, err)
return
}
files = append(files, path)
}
h.desktop.DropFiles(X, Y, files)
utils.HttpSuccess(w) utils.HttpSuccess(w)
} }