Skip to content
Snippets Groups Projects
Commit 088d5d4c authored by Janne Mareike Koschinski's avatar Janne Mareike Koschinski
Browse files

Improved upload API

parent 023dd900
Branches
No related tags found
No related merge requests found
......@@ -92,13 +92,7 @@ func pageUpload(ctx PageContext) http.Handler {
}
}
var images []Image
var ids []string
m := r.MultipartForm
files := m.File["file"]
for _, header := range files {
file, err := header.Open()
file, header, err := r.FormFile("file")
if err != nil {
if err = returnJson(w, []Result{{
Success: false,
......@@ -119,13 +113,7 @@ func pageUpload(ctx PageContext) http.Handler {
return
}
images = append(images, image)
ids = append(ids, image.Id)
}
pubsub := ctx.Redis.Subscribe(ctx.Config.ResultChannel)
waiting := make(map[string]bool)
for _, image := range images {
_, err = ctx.Database.Exec("INSERT INTO images (id, owner, created_at, original_name, type) VALUES ($1, $2, $3, $4, $5)", image.Id, user.Id, image.CreatedAt, image.OriginalName, image.MimeType)
if err != nil {
panic(err)
......@@ -146,11 +134,8 @@ func pageUpload(ctx PageContext) http.Handler {
ctx.Redis.RPush(fmt.Sprintf("queue:%s", ctx.Config.ImageQueue), data)
fmt.Printf("Submitted task %s at %d\n", image.Id, time.Now().Unix())
waiting[image.Id] = true
}
var results []Result
for len(waiting) != 0 {
waiting := true
for waiting {
message, err := pubsub.ReceiveMessage()
if err != nil {
if err = returnJson(w, []Result{{
......@@ -176,15 +161,13 @@ func pageUpload(ctx PageContext) http.Handler {
fmt.Printf("Returned task %s at %d\n", result.Id, time.Now().Unix())
if _, ok := waiting[result.Id]; ok {
delete(waiting, result.Id)
if result.Id == image.Id {
waiting = false
results = append(results, result)
if err = returnJson(w, result); err != nil {
panic(err)
}
}
if err = returnJson(w, results); err != nil {
panic(err)
}
return
} else {
......
......@@ -30,6 +30,17 @@
<div class="uploading images"></div>
</div>
<script>
function postData(url, data) {
return fetch(url, {
body: data,
cache: 'no-cache',
credentials: 'same-origin',
method: 'POST',
mode: 'cors',
redirect: 'follow'
}).then(response => response.json())
}
const form = document.querySelector("form.upload");
const element = document.querySelector("form.upload input[type=file]");
const results = document.querySelector(".uploading.images");
......@@ -46,15 +57,9 @@
results.appendChild(node);
const data = new FormData();
data.append("file", file);
data.append("file", file, file.name);
fetch("/upload", {
method: "POST",
credentials: "same-origin",
body: data
}).then((response) => {
return response.json()
}).then((json) => {
postData("/upload/", data).then((json) => {
const text = document.createElement("pre");
text.innerText = JSON.stringify(json);
node.appendChild(text);
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment