diff --git a/api/api.go b/api/api.go index b89346f..6cbe09d 100644 --- a/api/api.go +++ b/api/api.go @@ -5,8 +5,8 @@ import ( "encoding/json" "errors" "fmt" + "io" "io/ioutil" - "log" "mime/multipart" "net/http" ) @@ -116,50 +116,55 @@ func (a *API) UploadDocument(bucket string, file_header *multipart.FileHeader) ( a.Port, ) - route := fmt.Sprintf("/v1/bucket/%s", bucket) + url := fmt.Sprintf("%s/v1/bucket/%s", endpoint, bucket) - request := fmt.Sprintf("%s%s", endpoint, route) + // Create a new multipart writer + body := &bytes.Buffer{} + writer := multipart.NewWriter(body) - client := &http.Client{} - - // set the HTTP method, url, and request body - req, err := http.NewRequest(http.MethodPost, request, nil) + // Add the file to the request + file, err := file_header.Open() if err != nil { - return "", err + return "", fmt.Errorf("UploadDocument#file_header.Open: %s", err) } + defer file.Close() + + part, err := writer.CreateFormFile("document", file_header.Filename) + if err != nil { + return "", fmt.Errorf("UploadDocument#writer.CreateFormFile: %s", err) + } + + _, err = io.Copy(part, file) + if err != nil { + return "", fmt.Errorf("UploadDocument#io.Copy: %s", err) + } + + err = writer.Close() + if err != nil { + return "", fmt.Errorf("UploadDocument#writer.Close: %s", err) + } + + // Create a new HTTP request with the multipart body + req, err := http.NewRequest(http.MethodPost, url, body) + if err != nil { + return "", fmt.Errorf("UploadDocument#http.NewRequest: %s", err) + } + + req.Header.Set("Content-Type", writer.FormDataContentType()) if a.Opts.KeyAuth { - req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.Opts.Key)) + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", a.Opts.Key)) } - req.Header.Add("Content-Type", "multipart/form-data") - - // CreateFormFile with multipart.NewWriter - //TODO - /* - buf := new(bytes.Buffer) - form := multipart.NewWriter(buf) - form.CreateFormFile("document", ) - */ - - //TODO - log.Println("req: ", req) - - file, file_header, err := req.FormFile("document") - if err != nil { - log.Println("Error during http#Request.Formfile") - return "", err - } - - log.Println("file: ", file, "file_header: ", file_header) - log.Println("file_header: ", file_header) - + // Send the HTTP request + client := &http.Client{} resp, err := client.Do(req) if err != nil { - log.Println("Error during http#Client.Do") - return "", err + return "", fmt.Errorf("UploadDocument#client.Do: %s", err) } + defer resp.Body.Close() + // Handle the response var res map[string]interface{} json.NewDecoder(resp.Body).Decode(&res) diff --git a/cmd/server.go b/cmd/server.go index a19fd5d..b0d55eb 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -386,7 +386,7 @@ func handleV1DocumentCreate(c echo.Context) error { bucket := c.Param("bucket") - form_file, err := c.FormFile("file") + form_file, err := c.FormFile("document") if err != nil { log.Println(err) return c.JSON(http.StatusBadRequest, map[string]interface{}{