Ниже приведен мой файл main.go для загрузки изображений.
Здесь, используя этот файл go, я создаю образ докера.
Сборка докера прошла успешно.
Получив доступ к URL-адресу сервиса minikube, получите возможность загружать, перечислять и удалять файлы.
Но как только вы нажмете на кнопку «Загрузить файл», вы не сможете получить доступ к сайту.
var baseDirectory string
var ipaddress string
func main() {
baseDirectory = "/usr/local/go/" // provide the base directory path where the files will be kept
ipaddress = "localhost" // provide the ip address of the webserver
http.HandleFunc("/", homePage)
http.HandleFunc("/uploadfile", uploadFile)
fs := http.FileServer(http.Dir("static/"))
http.Handle("/static/", http.StripPrefix("/static/", fs))
err := http.ListenAndServe(":80", nil)
if err != nil {
fmt.Println("Error occurred ", err)
}
}
func homePage(w http.ResponseWriter, req *http.Request) {
var options [1]string
options[0] = "</br><a href = \"http://" + ipaddress + ":80/uploadfile\">Click to upload file</a></br>"
w.Header().Set("CONTENT-TYPE", "text/html; charset=UTF-8")
fmt.Fprintf(w, "<h1>%s</h1>, <div>%s</div>", "Home Page\n", options)
}
func uploadFile(w http.ResponseWriter, req *http.Request) {
//var s string
if req.Method == http.MethodPost {
f, handler, err := req.FormFile("usrfile")
if err != nil {
log.Println(err)
http.Error(w, "Error uploading file", http.StatusInternalServerError)
return
}
defer f.Close()
filename := handler.Filename
fmt.Println(filename)
bs, err := ioutil.ReadAll(f)
if err != nil {
log.Println(err)
http.Error(w, "Error reading file", http.StatusInternalServerError)
return
}
fmt.Println(bs)
err1 := ioutil.WriteFile(baseDirectory+filename, bs, 0644)
if err != nil {
log.Fatal(err1)
}
fmt.Println("Success!")
}
w.Header().Set("CONTENT-TYPE", "text/html; charset=UTF-8")
fmt.Fprintf(w, `<form action="/uploadfile" method="post" enctype="multipart/form-data">
Upload a file<br>
<input type="file" name="usrfile"><br>
<input type="submit">
</form>
<br>
<br>`)
}