Tuesday, 17 November 2020

golang 19 upload file to server

upload from desktop

upload from phone

file uploaded to upload folder on server
//cmd - server
C:\Users\bob\golang10>go run main.go
Uploaded File: SSMS-Setup-ENU.exe
File Size: 841083616
MIME Header: map[Content-Disposition:[form-data; name="myFile"; filename="SSMS-Setup-ENU.exe"] Content-Type:[application/x-msdownload]]
SSMS-Setup-ENU.exe uploaded

---------------------------------
//main.go
package main

import (
"fmt"
"html/template"
"io"
"net/http"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"

"github.com/gorilla/mux"
)

var templates *template.Template
var uploadPath = rootDir() + "\\golang10\\upload\\"

func indexGetHandler(w http.ResponseWriter, r *http.Request) {

templates.ExecuteTemplate(w, "index.html", nil)
}

func indexPostHandler(w http.ResponseWriter, r *http.Request) {

uploadFile(w, r)
}

func uploadFile(w http.ResponseWriter, r *http.Request) {

r.ParseMultipartForm(1000)

file, handler, err := r.FormFile("myFile")
if err != nil {
fmt.Println("Error Retrieving the File")
fmt.Println(err)
return
}
defer file.Close()
fmt.Printf("Uploaded File: %+v\n", handler.Filename)
fmt.Printf("File Size: %+v\n", handler.Size)
fmt.Printf("MIME Header: %+v\n", handler.Header)

path := uploadPath + handler.Filename
resFile, err := os.Create(path)
if err != nil {
fmt.Println(err)
}
defer resFile.Close()

io.Copy(resFile, file)
fmt.Println(handler.Filename, "uploaded")
}

func rootDir() string {
_, b, _, _ := runtime.Caller(0)
d := path.Join(path.Dir(b))
return filepath.Dir(d)
}

func open(url string) error {
var cmd string
var args []string

switch runtime.GOOS {
case "windows":
cmd = "cmd"
args = []string{"/c", "start"}
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
}
args = append(args, url)
return exec.Command(cmd, args...).Start()
}

func main() {
templates = template.Must(template.ParseGlob("templates/*.html"))
r := mux.NewRouter()
r.HandleFunc("/", indexGetHandler).Methods("GET")
r.HandleFunc("/", indexPostHandler).Methods("POST")
fs := http.FileServer(http.Dir("./static/"))
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", fs))
http.Handle("/", r)
//open("http://localhost:8000/")
http.ListenAndServe(":8000", nil)
}

--------------------------
//index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <title>File Upload</title>
</head>

<body>
    <div style="text-align: center;">
        <h1>Upload file to server </h1>
    </div>
    <form id="upload_form" enctype="multipart/form-data" method="post">
        <input type="file" name="myFile" id="myFile" onchange="uploadFile()"><br>
        <progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
        <h3 id="status"></h3>
        <p id="loaded_n_total"></p>
    </form>
    <script>
        function _(el) {
            return document.getElementById(el);
        }

        function uploadFile() {
            var file = _("myFile").files[0];
            //alert(file.name + " | " + file.size + " | " + file.type);
            var formdata = new FormData();
            formdata.append("myFile", file);
            var ajax = new XMLHttpRequest();
            ajax.upload.addEventListener("progress", progressHandler, false);
            ajax.addEventListener("load", completeHandler, false);
            ajax.addEventListener("error", errorHandler, false);
            ajax.addEventListener("abort", abortHandler, false);
            ajax.open("POST", "http://192.168.0.18:8000/"); // http://www.developphp.com/video/JavaScript/File-Upload-Progress-Bar-Meter-Tutorial-Ajax-PHP
            //use file_upload_parser.php from above url
            ajax.send(formdata);
        }

        function progressHandler(event) {
            _("loaded_n_total").innerHTML = "Uploaded " + event.loaded + " bytes of " + event.total;
            var percent = (event.loaded / event.total) * 100;
            _("progressBar").value = Math.round(percent);
            _("status").innerHTML = Math.round(percent) + "% uploaded... please wait";
        }

        function completeHandler(event) {
            _("status").innerHTML = event.target.responseText;
            _("progressBar").value = 0; //wil clear progress bar after successful upload
        }

        function errorHandler(event) {
            _("status").innerHTML = "Upload Failed";
        }

        function abortHandler(event) {
            _("status").innerHTML = "Upload Aborted";
        }
    </script>
</body>

</html>

No comments:

Post a Comment