Created
June 15, 2014 16:03
-
-
Save cryptix/1a60a4c513c46f4e77ab to your computer and use it in GitHub Desktop.
revel image upload example
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
package controllers | |
import ( | |
"bytes" | |
"image" | |
"image/gif" | |
"image/jpeg" | |
"image/png" | |
"io" | |
"net/http" | |
"strings" | |
"github.com/nfnt/resize" | |
"github.com/revel/revel" | |
"corp/WebAdmin/app/routes" | |
"corp/models" | |
) | |
type Fotos struct { | |
App | |
} | |
func (c Fotos) Save(f models.Foto, imagefile io.Reader) revel.Result { | |
headers, ok := c.Params.Files["imagefile"] | |
if ok { | |
if len(headers) != 1 { | |
return c.RenderError(SaveFotoError{msg: "only one file at a time."}) | |
} | |
var ( | |
err error | |
bildBuf bytes.Buffer | |
nameSplit []string | |
suffix string | |
uploadDaten image.Image | |
) | |
nameSplit = strings.Split(strings.ToLower(headers[0].Filename), ".") | |
if len(nameSplit) <= 1 { | |
return c.RenderError(SaveFotoError{msg: "no file suffix."}) | |
} | |
suffix = nameSplit[len(nameSplit)-1] | |
switch { | |
case suffix == "jpg" || suffix == "jpeg": | |
uploadDaten, err = jpeg.Decode(imagefile) | |
if err != nil { | |
return c.RenderError(SaveFotoError{"jpeg.Decode() failed", err}) | |
} | |
case suffix == "png": | |
uploadDaten, err = png.Decode(imagefile) | |
if err != nil { | |
return c.RenderError(SaveFotoError{"png.Decode() failed", err}) | |
} | |
case suffix == "gif": | |
uploadDaten, err = gif.Decode(imagefile) | |
if err != nil { | |
return c.RenderError(SaveFotoError{"gif.Decode() failed", err}) | |
} | |
default: | |
return c.RenderError(SaveFotoError{msg: "unsupported image suffix"}) | |
} | |
resized := resize.Resize(500, 0, uploadDaten, resize.Lanczos3) | |
err = png.Encode(&bildBuf, resized) | |
if err != nil { | |
return c.RenderError(SaveFotoError{"png.Encode() failed", err}) | |
} | |
f.Data = bildBuf.Bytes() | |
f.Width = resized.Bounds().Dx() | |
f.Height = resized.Bounds().Dy() | |
c.Flash.Success("Bild gespeichert") | |
} | |
f.Save(c.Txn) | |
return c.Redirect(routes.Fotos.Index(false, f.HerstellerId)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
struct Foto ???