Repository navigation
Replies: 1 comment
|
You can do it all from func upload(c echo.Context) error {
fh, err := c.FormFile("file")
if err != nil {
return err
}
src, err := fh.Open()
if err != nil {
return err
}
defer src.Close()
// Read up to 512 bytes (all DetectContentType looks at)
buf := make([]byte, 512)
n, err := io.ReadFull(src, buf)
if err != nil && err != io.EOF && err != io.ErrUnexpectedEOF {
return err
}
mimeType := http.DetectContentType(buf[:n])
allowed := map[string]bool{"image/png": true, "image/jpeg": true}
if !allowed[mimeType] {
return echo.NewHTTPError(http.StatusUnsupportedMediaType, "file type not allowed: "+mimeType)
}
// Rewind before saving, otherwise the first 512 bytes are lost
if _, err := src.Seek(0, io.SeekStart); err != nil {
return err
}
// ... copy src to its destination as in the docs example
return c.String(http.StatusOK, "uploaded")
}Notes:
|
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Hello!
I'm trying to implement a file uploader with Echo. The example in the official documentation looks great, but then I want to restrict the file type that can be uploaded.
With the regular
net/httppackage, there's this way to get the MIME filetype of it:However, when working with
echo.Context, it has thec.FileHeader()method, which only returns a*multipart.FileHeader.EDIT
Holy, I must had been out of my mind when I started this thread. with
*multipart.FileHeader.Open()I already got themultipart.Filethat I need.Is there a good way to check the file type using only
echo.Context?Thanks in advance!
All reactions