Reputation: 1085
I'm trying to upload a file via XMLHttpRequest, currently i'm using golang
When I use CURL to test the upload everything goes fine, and the file is uploaded to Amazon S3 bucket, but when using Javascript I get the following error : multipart: NextPart: EOF
this is the JS part :
document.getElementById("attachment").addEventListener("change", function(e) {
var file = this.files[0];
var xhr = new XMLHttpRequest();
var formdata = new FormData();
formdata.append("attachment", file);
boundary=Math.random().toString().substr(2);
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(["xhr upload complete", e]);
}
};
xhr.open("POST", "https://upload_host:8443/upload", true);
xhr.setRequestHeader("Content-Type","multipart/form-data; charset=utf-8; boundary=---------------------------"+boundary+";");
xhr.send(formdata);
}, false);
For the go handler :
func upload_handler(w http.ResponseWriter, r *http.Request, m render.Render) {
w.Header().Set("Access-Control-Allow-Origin", "*")
file, header, err := r.FormFile("C.Storage.FieldName")
if err != nil {
// ERROR THROWN HERE
ServeHTTP(400, err.Error(), m)
return
}
content, err := ioutil.ReadAll(file)
if err != nil {
ServeHTTP(400, err.Error(), m)
return
}
fileSize, err := file.Seek(0, 2) //2 = from end
if err != nil {
ServeHTTP(400, err.Error(), m)
return
}
if fileSize > int64(C.Storage.FileSize) {
ServeHTTP(400, "File size limit exceeded", m)
return
}
ftype := http.DetectContentType(content)
if !strings.Contains(C.Storage.AllowedMimes, ftype) {
ServeHTTP(400, "File type not allowed", m)
return
}
//FUNCTION TO UPLOAD TO AMAZON S3
file.Close()
}
Upvotes: 1
Views: 1940
Reputation: 1362
For uploading you can use PlUploader Code example (that is also used for large file uploading).
Upvotes: 1