I'm trying to upload an image to the s3 bucket using GoLang. I have mentioned function body of program. Which takes an image file as multipart form data and a file name which I should to save the image in s3.
func uploadImage(res http.ResponseWriter, req *http.Request) {
file, handler, err := req.FormFile("uploaded_file") // uploaded_file is the key(input field name) of the form-data
if err != nil {
fmt.Println(err)
return
}
type Resp struct {
Status string `json:"status"`
Filename string `json:"filename"`
}
filename := req.Form.Get("filename")
rnd := render.New()
var Response Resp
Response.Status = "failed"
if filename != "" {
// define credentials
awsAccessKey := "KEY"
awsSecret := "SECRET"
token := ""
// set credentials
creds := credentials.NewStaticCredentials(awsAccessKey, awsSecret, token)
credentials, err := creds.Get()
if err != nil {
fmt.Printf("bad credentials: %s", err)
}
fmt.Println(credentials)
//setup config and s3 settings
cfg := aws.NewConfig().WithRegion("ap-southeast-1").WithCredentials(creds)
//create s3 credentail
svc := s3.New(session.New(), cfg)
type Sizer interface {
Size() int64
}
size := file.(Sizer).Size()
// create a buffer of size = images size
buffer := make([]byte, size)
file.Read(buffer)
fileBytes := bytes.NewReader(buffer)
fileType := http.DetectContentType(buffer)
path := "mybucketname/" + filename
params := &s3.PutObjectInput{
Bucket: aws.String("mybucketname"),
Key: aws.String(path),
Body: fileBytes,
ContentLength: aws.Int64(size),
ContentType: aws.String(fileType),
ACL: aws.String("public-read"),
}
resp, err := svc.PutObject(params)
if err != nil {
fmt.Printf("bad response: %s", err)
}
fmt.Printf("response %s", awsutil.StringValue(resp))
Response.Status = "success"
Response.Filename = awsutil.StringValue(resp)
}
defer file.Close()
res.Header().Set("Content-Type", "application/json")
rnd.JSON(res, http.StatusOK, Response)
}
This function returns the status as success on successful upload of the image and the file name as http response.
In console I can see some response as :
response {
ETag: "\"bd9be6ada974e66a154552edc78b4a81\""
}
I've no clue on what ETag means, but I understood that the image is uploaded and I got some positive response from s3. But I'm unable to find the image that I've uploaded in s3.
I need some help to solve this. Thanks in advance.
ETagmeans. - kostix