photoprism/internal/api/upload.go

58 lines
1.4 KiB
Go
Raw Normal View History

2019-06-13 20:26:01 +02:00
package api
import (
"fmt"
"net/http"
"os"
"path/filepath"
"time"
"github.com/photoprism/photoprism/internal/config"
"github.com/photoprism/photoprism/internal/util"
log "github.com/sirupsen/logrus"
"github.com/gin-gonic/gin"
)
// POST /api/v1/upload/:path
2019-06-13 20:26:01 +02:00
func Upload(router *gin.RouterGroup, conf *config.Config) {
router.POST("/upload/:path", func(c *gin.Context) {
2019-06-13 20:26:01 +02:00
start := time.Now()
subPath := c.Param("path")
2019-06-13 20:26:01 +02:00
form, err := c.MultipartForm()
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": util.UcFirst(err.Error())})
return
}
log.Debugf("Value: %#v", form.Value)
log.Debugf("File: %#v", form.File)
files := form.File["files"]
path := fmt.Sprintf("%s/upload/%s", conf.ImportPath(), subPath)
2019-06-13 20:26:01 +02:00
if err := os.MkdirAll(path, os.ModePerm); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": util.UcFirst(err.Error())})
return
}
for _, file := range files {
filename := fmt.Sprintf("%s/%s", path, filepath.Base(file.Filename))
if err := c.SaveUploadedFile(file, filename); err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": util.UcFirst(err.Error())})
return
}
}
elapsed := time.Since(start)
log.Infof("%d files uploaded in %s", len(files), elapsed)
2019-06-13 20:26:01 +02:00
2019-06-14 22:01:58 +02:00
c.JSON(http.StatusOK, gin.H{"message": fmt.Sprintf("%d files uploaded in %s", len(files), elapsed)})
2019-06-13 20:26:01 +02:00
})
}