Как загружать файлы на сервер golang?
Можете, пожалуйста, привести пример со стороны go и JavaScript?
1 ответ
https://github.com/golang-book/bootcamp-examples/blob/master/week2/day3/file-upload-example/main.go
package main
import (
"net/http"
"io"
"os"
"path/filepath"
"fmt"
)
func main() {
fmt.Println("TEMP DIR:", os.TempDir())
http.ListenAndServe(":9000", http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.Method == "POST" {
src, hdr, err := req.FormFile("my-file")
if err != nil {
http.Error(res, err.Error(), 500)
return
}
defer src.Close()
dst, err := os.Create(filepath.Join(os.TempDir(), hdr.Filename))
if err != nil {
http.Error(res, err.Error(), 500)
return
}
defer dst.Close()
io.Copy(dst, src)
}
res.Header().Set("Content-Type", "text/html")
io.WriteString(res, `
<form method="POST" enctype="multipart/form-data">
<input type="file" name="my-file">
<input type="submit">
</form>
`)
}))
}