Example #1
0
func upload(w http.ResponseWriter, r *http.Request) {
	session, err := store.Get(r, "flash-session")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
	err = r.ParseMultipartForm(10 << 20)
	if err != nil {
		log.Println("ParseMultipartForm error:", err)
		return
	}
	pid := r.FormValue("pid")
	tags := r.FormValue("tags")
	hostTags := []string{}
	if tags != "" {
		hostTags = strings.Split(tags, ",")
	}
	settings := &drone.Settings{ProjectID: pid, Tags: hostTags}
	var wg sync.WaitGroup
	for _, fheaders := range r.MultipartForm.File {
		for _, header := range fheaders {
			wg.Add(1)
			go func(header *multipart.FileHeader, w *sync.WaitGroup) {
				defer w.Done()
				f, err := header.Open()
				if err != nil {
					log.Println("file open error", err)
				}
				var buff bytes.Buffer
				buff.ReadFrom(f)
				f.Close()
				err = processFile(settings, buff.Bytes())
				if err != nil {
					errmsg := fmt.Sprintf("%s: %s", err, header.Filename)
					log.Println(errmsg)
					session.AddFlash(errmsg, "alert alert-danger")
				} else {
					goodmsg := fmt.Sprintf("Upload Successful %s", header.Filename)
					log.Println(goodmsg)
					session.AddFlash(goodmsg, "alert alert-success")
				}
			}(header, &wg)
		}
	}
	wg.Wait()
	session.Save(r, w)
	http.Redirect(w, r, "/", 302)
}