Created
April 14, 2021 04:59
-
-
Save vedashree29296/c2734449215d2041c00cdc6a3a3ec414 to your computer and use it in GitHub Desktop.
Upload Handler for petstore Go chronicles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var imageDir string = "images" | |
func UploadPetImage(c echo.Context) error { | |
// Get id from Multipart form data | |
id, err := strconv.Atoi(c.FormValue("id")) | |
// get file form form data | |
file, err := c.FormFile("file") | |
if err != nil { | |
return echo.NewHTTPError(http.StatusBadRequest, "Couldn't read file from form value") | |
} | |
// Read Source file | |
src, err := file.Open() | |
if err != nil { | |
return echo.NewHTTPError(http.StatusInternalServerError, "Couldn't open file") | |
} | |
defer src.Close() | |
// Create Destination | |
dstPath := filepath.Join(imageDir, file.Filename) | |
dst, err := os.Create(dstPath) | |
if err != nil { | |
return echo.NewHTTPError(http.StatusInternalServerError, "Couldn't create destination file") | |
} | |
defer dst.Close() | |
// Copy source to destination | |
if _, err = io.Copy(dst, src); err != nil { | |
return echo.NewHTTPError(http.StatusInternalServerError, "Couldn't copy file") | |
} | |
// Update database | |
err = service.UpdateImageURL(&db.Pet{ID: id, ImageURL: dstPath}) | |
if err != nil { | |
return echo.NewHTTPError(http.StatusInternalServerError, "Couldn't read file") | |
} | |
return c.JSON(http.StatusCreated, "File uploaded successfully") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment