Fix upload problems

This commit is contained in:
Las Zenow 2013-07-16 22:56:48 +02:00
parent 61764d51b3
commit bf0480868d

View file

@ -18,52 +18,63 @@ func InitUpload() {
var uploadChannel chan uploadRequest var uploadChannel chan uploadRequest
type uploadRequest struct { type uploadRequest struct {
epubs []*multipart.FileHeader file multipart.File
filename string
} }
func uploadWorker() { func uploadWorker() {
for req := range uploadChannel { for req := range uploadChannel {
for _, f := range req.epubs { processFile(req)
file, err := f.Open() }
if err != nil {
log.Println("Can not open uploaded file", f.Filename, ":", err)
continue
} }
defer file.Close()
epub, err := openMultipartEpub(file) func processFile(req uploadRequest) {
defer req.file.Close()
epub, err := openMultipartEpub(req.file)
if err != nil { if err != nil {
log.Println("Not valid epub uploaded file", f.Filename, ":", err) log.Println("Not valid epub uploaded req.file", req.filename, ":", err)
continue return
} }
defer epub.Close() defer epub.Close()
book := parseFile(epub) book := parseFile(epub)
title, _ := book["title"].(string) title, _ := book["title"].(string)
file.Seek(0, 0) req.file.Seek(0, 0)
id, err := StoreNewFile(title+".epub", file) id, err := StoreNewFile(title+".epub", req.file)
if err != nil { if err != nil {
log.Println("Error storing book (", title, "):", err) log.Println("Error storing book (", title, "):", err)
continue return
} }
book["file"] = id book["req.file"] = id
db.InsertBook(book) db.InsertBook(book)
log.Println("File uploaded:", f.Filename) log.Println("File uploaded:", req.filename)
}
}
} }
func uploadPostHandler(w http.ResponseWriter, r *http.Request, sess *Session) { func uploadPostHandler(w http.ResponseWriter, r *http.Request, sess *Session) {
problem := false
r.ParseMultipartForm(20000000) r.ParseMultipartForm(20000000)
filesForm := r.MultipartForm.File["epub"] filesForm := r.MultipartForm.File["epub"]
uploadChannel <- uploadRequest{filesForm} for _, f := range filesForm {
file, err := f.Open()
if err != nil {
log.Println("Can not open uploaded file", f.Filename, ":", err)
sess.Notify("Upload problem!", "There was a problem with book "+f.Filename, "error")
problem = true
continue
}
uploadChannel <- uploadRequest{file, f.Filename}
}
if !problem {
if len(filesForm) > 0 { if len(filesForm) > 0 {
sess.Notify("Upload successful!", "Thank you for your contribution", "success") sess.Notify("Upload successful!", "Thank you for your contribution", "success")
} else { } else {
sess.Notify("Upload problem!", "No books where uploaded.", "error") sess.Notify("Upload problem!", "No books where uploaded.", "error")
} }
}
uploadHandler(w, r, sess) uploadHandler(w, r, sess)
} }