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"
|
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
)
|
|
|
|
|
2019-06-14 21:16:59 +02:00
|
|
|
// POST /api/v1/upload/:path
|
2019-06-13 20:26:01 +02:00
|
|
|
func Upload(router *gin.RouterGroup, conf *config.Config) {
|
2019-06-14 21:16:59 +02:00
|
|
|
router.POST("/upload/:path", func(c *gin.Context) {
|
2019-07-02 22:03:23 +02:00
|
|
|
if conf.ReadOnly() {
|
|
|
|
c.AbortWithStatusJSON(http.StatusForbidden, ErrReadOnly)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-11-11 21:10:41 +01:00
|
|
|
if Unauthorized(c, conf) {
|
|
|
|
c.AbortWithStatusJSON(http.StatusUnauthorized, ErrUnauthorized)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-06-13 20:26:01 +02:00
|
|
|
start := time.Now()
|
2019-06-14 21:16:59 +02:00
|
|
|
subPath := c.Param("path")
|
2019-06-13 20:26:01 +02:00
|
|
|
|
2019-12-05 19:21:35 +01:00
|
|
|
f, err := c.MultipartForm()
|
2019-06-13 20:26:01 +02:00
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": util.UcFirst(err.Error())})
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-12-05 19:21:35 +01:00
|
|
|
files := f.File["files"]
|
2019-06-13 20:26:01 +02:00
|
|
|
|
2019-06-14 21:16:59 +02:00
|
|
|
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)
|
|
|
|
|
2019-06-14 21:16:59 +02:00
|
|
|
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
|
|
|
})
|
|
|
|
}
|