Ajouter upload de fichier par form html #49

Merged
vlbeaudoin merged 7 commits from feature/admin-route into main 2023-04-28 19:33:30 -04:00
2 changed files with 52 additions and 29 deletions
Showing only changes of commit 3dd4dd6e29 - Show all commits

View file

@ -26,6 +26,17 @@ type APIOptions struct {
Password string Password string
} }
type UploadDocumentResponse struct {
Info UploadDocumentResponseInfo `json:"info"`
Message string `json:"message"`
}
type UploadDocumentResponseInfo struct {
Bucket string `json:"bucket"`
Object string `json:"key"`
Size float64 `json:"size"`
}
func New(protocol, host string, port int, opts APIOptions) (*API, error) { func New(protocol, host string, port int, opts APIOptions) (*API, error) {
api := API{ api := API{
Protocol: protocol, Protocol: protocol,
@ -109,7 +120,7 @@ func (a *API) Call(method, route string) ([]byte, error) {
return nil, errors.New(fmt.Sprintf("method must be 'GET' or 'DELETE', got '%s'", method)) return nil, errors.New(fmt.Sprintf("method must be 'GET' or 'DELETE', got '%s'", method))
} }
func (a *API) UploadDocument(bucket string, file_header *multipart.FileHeader) (map[string]interface{}, error) { func (a *API) UploadDocument(bucket string, file_header *multipart.FileHeader) (UploadDocumentResponse, error) {
endpoint := fmt.Sprintf("%s://%s:%d", endpoint := fmt.Sprintf("%s://%s:%d",
a.Protocol, a.Protocol,
a.Host, a.Host,
@ -125,29 +136,29 @@ func (a *API) UploadDocument(bucket string, file_header *multipart.FileHeader) (
// Add the file to the request // Add the file to the request
file, err := file_header.Open() file, err := file_header.Open()
if err != nil { if err != nil {
return nil, fmt.Errorf("UploadDocument#file_header.Open: %s", err) return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#file_header.Open: %s", err)
} }
defer file.Close() defer file.Close()
part, err := writer.CreateFormFile("document", file_header.Filename) part, err := writer.CreateFormFile("document", file_header.Filename)
if err != nil { if err != nil {
return nil, fmt.Errorf("UploadDocument#writer.CreateFormFile: %s", err) return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#writer.CreateFormFile: %s", err)
} }
_, err = io.Copy(part, file) _, err = io.Copy(part, file)
if err != nil { if err != nil {
return nil, fmt.Errorf("UploadDocument#io.Copy: %s", err) return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#io.Copy: %s", err)
} }
err = writer.Close() err = writer.Close()
if err != nil { if err != nil {
return nil, fmt.Errorf("UploadDocument#writer.Close: %s", err) return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#writer.Close: %s", err)
} }
// Create a new HTTP request with the multipart body // Create a new HTTP request with the multipart body
req, err := http.NewRequest(http.MethodPost, url, body) req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil { if err != nil {
return nil, fmt.Errorf("UploadDocument#http.NewRequest: %s", err) return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#http.NewRequest: %s", err)
} }
req.Header.Set("Content-Type", writer.FormDataContentType()) req.Header.Set("Content-Type", writer.FormDataContentType())
@ -160,12 +171,12 @@ func (a *API) UploadDocument(bucket string, file_header *multipart.FileHeader) (
client := &http.Client{} client := &http.Client{}
resp, err := client.Do(req) resp, err := client.Do(req)
if err != nil { if err != nil {
return nil, fmt.Errorf("UploadDocument#client.Do: %s", err) return UploadDocumentResponse{}, fmt.Errorf("UploadDocument#client.Do: %s", err)
} }
defer resp.Body.Close() defer resp.Body.Close()
// Handle the response // Handle the response
var res map[string]interface{} var res UploadDocumentResponse
json.NewDecoder(resp.Body).Decode(&res) json.NewDecoder(resp.Body).Decode(&res)
return res, nil return res, nil

View file

@ -9,6 +9,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
"regexp"
"embed" "embed"
"html/template" "html/template"
@ -388,7 +389,6 @@ func handleV1DocumentCreate(c echo.Context) error {
form_file, err := c.FormFile("document") form_file, err := c.FormFile("document")
if err != nil { if err != nil {
log.Println(err)
return c.JSON(http.StatusBadRequest, map[string]interface{}{ return c.JSON(http.StatusBadRequest, map[string]interface{}{
"message": "Error during handleV1DocumentCreate's echo#Context.FormFile", "message": "Error during handleV1DocumentCreate's echo#Context.FormFile",
"error": err, "error": err,
@ -403,11 +403,6 @@ func handleV1DocumentCreate(c echo.Context) error {
} }
if !allowed { if !allowed {
/*
return c.JSON(http.StatusBadRequest, map[string]string{
"message": "Bucket is not allowed in server.documents.buckets",
})
*/
return c.JSON(http.StatusNotFound, map[string]string{"message": "Not Found"}) return c.JSON(http.StatusNotFound, map[string]string{"message": "Not Found"})
} }
@ -432,7 +427,14 @@ func handleV1DocumentCreate(c echo.Context) error {
} }
defer src.Close() defer src.Close()
info, err := client.PutObject(ctx, bucket, form_file.Filename, src, form_file.Size, minio.PutObjectOptions{ reg, err := regexp.Compile("[^.a-zA-Z0-9_-]+")
if err != nil {
return c.Render(http.StatusInternalServerError, "documentation-html", nil)
}
filename_processed := reg.ReplaceAllString(form_file.Filename, "")
info, err := client.PutObject(ctx, bucket, filename_processed, src, form_file.Size, minio.PutObjectOptions{
ContentType: form_file.Header.Get("Content-Type"), ContentType: form_file.Header.Get("Content-Type"),
}) })
if err != nil { if err != nil {
@ -671,21 +673,39 @@ func handleDocumentation(c echo.Context) error {
var data []Bucket var data []Bucket
for _, bucket := range buckets { for _, bucket := range buckets {
result, err := client.Call(http.MethodGet, fmt.Sprintf("/v1/bucket/%s", bucket)) content, err := client.Call(http.MethodGet, fmt.Sprintf("/v1/bucket/%s", bucket))
if err != nil { if err != nil {
return c.Render(http.StatusInternalServerError, "documentation-html", nil) return c.Render(http.StatusInternalServerError, "documentation-html", nil)
} }
var documents []string var documents []string
err = json.Unmarshal(result, &documents) err = json.Unmarshal(content, &documents)
if err != nil { if err != nil {
return c.Render(http.StatusInternalServerError, "documentation-html", nil) return c.Render(http.StatusInternalServerError, "documentation-html", nil)
} }
// Ce bloc retire tous les caractères spéciaux d'une string
// N'est pas présentement activé, car les fichiers sont processed
// à la création de toute façon.
/*
reg, err := regexp.Compile("[^.a-zA-Z0-9_-]+")
if err != nil {
return c.Render(http.StatusInternalServerError, "documentation-html", nil)
}
var documents_processed []string
for _, document := range documents {
document_processed := reg.ReplaceAllString(document, "")
documents_processed = append(documents_processed, document_processed)
}
*/
documents_processed := documents
data = append(data, Bucket{ data = append(data, Bucket{
Name: bucket, Name: bucket,
Documents: documents, Documents: documents_processed,
}) })
} }
@ -759,17 +779,9 @@ func handleAdminDocumentsUploadPOST(c echo.Context) error {
// Format response // Format response
var message, info, status string var message, info, status string
for key, value := range response { info = fmt.Sprintf("[%.0f] /public/documentation/%s/%s", response.Info.Size, response.Info.Bucket, response.Info.Object)
switch key {
case "info": status = response.Message
info_map, ok := value.(map[string]interface{})
if ok {
info = fmt.Sprintf("/public/documentation/%s/%s [%.2f]", info_map["bucket"], info_map["key"], info_map["size"])
}
case "message":
status = fmt.Sprint(value)
}
}
message = fmt.Sprintf("%s - %s", status, info) message = fmt.Sprintf("%s - %s", status, info)