Fix upload de documents depuis DocumentCreate

This commit is contained in:
Victor Lacasse-Beaudoin 2023-04-28 16:52:16 -04:00
parent 07005c8753
commit cc4ab5851d
2 changed files with 39 additions and 34 deletions

View file

@ -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)

View file

@ -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{}{