Skip to content

Instantly share code, notes, and snippets.

@vedashree29296
Created April 14, 2021 04:59
Show Gist options
  • Save vedashree29296/c2734449215d2041c00cdc6a3a3ec414 to your computer and use it in GitHub Desktop.
Save vedashree29296/c2734449215d2041c00cdc6a3a3ec414 to your computer and use it in GitHub Desktop.
Upload Handler for petstore Go chronicles
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