Skip to content

Instantly share code, notes, and snippets.

@noateden
Created February 17, 2020 04:38
Show Gist options
  • Save noateden/8467224c69b2f8c5074e0a0dda130c01 to your computer and use it in GitHub Desktop.
Save noateden/8467224c69b2f8c5074e0a0dda130c01 to your computer and use it in GitHub Desktop.
Example go service image file upload
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="file" id="file">
<div id="result">
</div>
</body>
<script>
window.onload = function () {
document.getElementById('file').addEventListener('change', (evt) => {
let formData = new FormData();
formData.append('image', evt.target.files[0]);
let postDataRequest = new XMLHttpRequest();
postDataRequest.open( 'POST',
'http://127.0.0.1:9000/upload/image',
true
);
postDataRequest.send(formData);
postDataRequest.onload = function () {
console.log(postDataRequest.responseText);
};
});
};
</script>
</html>
func (mw *Middleware) ValidateAddDataRequest(request *http.Request) (error, *domain.AddDataRequest) {
err := request.ParseMultipartForm(5 * 1024 * 1024)
if err != nil {
return err, nil
}
image, header, err := request.FormFile("image")
if err != nil {
return err, nil
}
fmt.Printf("%v - received %v\n", time.Now().Format(time.RFC850), header.Filename)
var buffer bytes.Buffer
_, _ = io.Copy(&buffer, image)
return nil, &domain.AddDataRequest{Data: buffer.Bytes()}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment