Example #1
0
func insertHandler(w http.ResponseWriter, r *auth.AuthenticatedRequest) {
	file, header, err := r.FormFile("file")
	if err != nil {
		log.Error("Invalid form data %v:%s", r.Header, err.Error())
		fmt.Fprintln(w, err)
		return
	}
	log.Debug("Insert handler started for file %s", header.Filename)
	tag := r.Request.Header.Get("File-Tag")
	if len(tag) == 0 {
		log.Error("No file-tag header")
		fmt.Fprintf(w, "No file-tag header")
		return
	}

	bytes, err := base64.StdEncoding.DecodeString(header.Filename)
	if err != nil {
		log.Error("Filename %s is not valid base64 string", header.Filename)
		fmt.Fprintf(w, "Filename is not valid base64 string")
		return
	}
	filename := string(bytes)

	id, err := RegisterFile(filename, tag, time.Now())
	if err != nil {
		log.Error("Unable to register file %s from %s in DB:%s", filename, r.Host, err.Error())
		fmt.Fprintf(w, "Unable to register file")
		return
	}

	path, dir, err := CreateFilePath(id)

	if err != nil {
		log.Error("Unable to create file path for %s from %s in DB:%s", filename, r.Host, err.Error())
		fmt.Fprintf(w, "Unable to create file path")
		return
	}

	out, err := os.Create(path)
	if err != nil {
		log.Error("Unable to save file %s from %s in DB:%s", filename, r.Host, err.Error())
		fmt.Fprintf(w, "Unable to save file")
		return
	}

	_, err = io.Copy(out, file)
	if err != nil {
		fmt.Fprintln(w, err)
	}

	out.Close()
	file.Close()
	err = SaveMetaData(id, filename, tag, dir)
	if err != nil {
		log.Error("can't save meta for %d:%s", id, err.Error())
	}
	err = ConfirmFile(id)
	if err != nil {
		log.Error("Unable to commit file %s from %s in DB:%s", filename, r.Host, err.Error())
		fmt.Fprintf(w, "Unable to commit file")
		return
	}
	w.Header().Add("File-Id", strconv.FormatInt(id, 10))
	fmt.Fprintf(w, "%d", id)
	log.Info("File %s from %s saved succesfully", filename, r.Host)
}