JSFiddle - React, Tailwind, and code Playground
HTML
<form enctype="multipart/form-data" action="http://127.0.0.1:9090/upload" method="post">
<input type="file" name="uploadfile" />
<input type="hidden" name="token" value="{{.}}"/>
<input type="submit" value="upload" />
</form>
CSS
xhr = new XMLHttpRequest();
xhr.onreadystatechange = (event) ->
if (event.target.readyState == 4)
if (event.target.status == 200)
console.log 'ok'
xhr.open('POST', '/uploadpub');
xhr.setRequestHeader('X-FILE-NAME', file.name);
xhr.send(file);
JavaScript
golang :
func UploadHandler(res http.ResponseWriter, req *http.Request, dirPath string) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(res, err.Error(), status)
}
}()
// parse request
const _24K = (1 << 20) * 24
if err = req.ParseMultipartForm(_24K); nil != err {
status = http.StatusInternalServerError
fmt.Println("ONE")
return
}
for _, fheaders := range req.MultipartForm.File {
for _, hdr := range fheaders {
// open uploaded
var infile multipart.File
if infile, err = hdr.Open(); nil != err {
status = http.StatusInternalServerError
fmt.Println("TWO")
return
}
// open destination
var outfile *os.File
if outfile, err = os.Create(GivePath() + dirPath + hdr.Filename); nil != err {
status = http.StatusInternalServerError
fmt.Println("THREE")
return
}
// 32K buffer copy
var written int64
if written, err = io.Copy(outfile, infile); nil != err {
status = http.StatusInternalServerError
fmt.Println("FOUR")
return
}
res.Write([]byte("uploaded file:" + hdr.Filename + ";length:" + strconv.Itoa(int(written))))
}
}
}