Wednesday, 18 November 2020

golang20 list the files in a folder

 C:\Users\bob\golang11>go run main.go
a.txt
SSMS-Setup-ENU.exe
w3school.jpg

------------------------
package main

import (
"fmt"
"log"
"os"
"path"
"path/filepath"
"runtime"
)

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

func main() {
dirname := rootDir() + "\\golang9\\download"

f, err := os.Open(dirname)
if err != nil {
log.Fatal(err)
}
files, err := f.Readdir(-1)
f.Close()
if err != nil {
log.Fatal(err)
}

for _, file := range files {
fmt.Println(file.Name())
}
}

Tuesday, 17 November 2020

Great Asian Railway Journeys

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>

Sunday, 15 November 2020

golang 18 http serve file

open download page by phone, available static files on server are displayed
press download icon

download shows progress


//main.go
package main

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

"github.com/gorilla/mux"
)

var templates *template.Template
var downloadPath = rootDir() + "\\golang9\\download\\"

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

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

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

r.ParseForm()
filename := r.PostForm.Get("filename")
downloadHandler(w, r, filename)
}

func downloadHandler(w http.ResponseWriter, r *http.Request, filename string) {
w.Header().Set("Content-Disposition", "attachment; filename="+strconv.Quote(filename))
w.Header().Set("Content-Type", "application/octet-stream")
path := downloadPath + filename
http.ServeFile(w, r, path)
}

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
<html>

<head>
    <title> Download</title>
    <link rel="stylesheet" type="text/css" href="/static/index.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>

<body>
    <div style="text-align: center;">
        <h1>Download file from server </h1>
    </div>

    <form method="POST">
        <input type="hidden" value="" id="input1" name="filename">
        <ul>
            <li>
                <h3>a.txt <i class="fa fa-download" onclick="download('a.txt')"></i></h3>
            </li>
            <li>
                <h3>w3school.jpg <i class="fa fa-download" onclick="download('w3school.jpg')"></i></h3>
            </li>
            <li>
                <h3>SSMS-Setup-ENU.exe <i class="fa fa-download" onclick="download('SSMS-Setup-ENU.exe')"></i></h3>
            </li>
        </ul>
        <button type="submit" id="button1" style="display: none;"></button>
    </form>


</body>
<script>
    function download(filename) {
        document.getElementById("input1").value = filename
        document.getElementById("button1").click()
    }
</script>

</html>
 
reference:

http.ServeFile

最慘雙11

Saturday, 14 November 2020

golang 17 file transfer

file copied from download folder to desktop
//cmd
C:\Users\bob\golang7>go run main.go
Bytes Written: 25698304

//main.go
package main

import (
"fmt"
"io"
"log"
"os"
"path/filepath"
)

// Copy a file
func main() {
// Open original file
originalFilepath := "C:\\Users\\bob\\Downloads\\mysql-installer-web-community-8.0.21.0.msi"
_, filename := filepath.Split(originalFilepath)

original, err := os.Open(originalFilepath)
if err != nil {
log.Fatal(err)
}
defer original.Close()

// Create new file
newFilepath := filepath.Join("c:\\Users\\bob\\Desktop", filename)
new, err := os.Create(newFilepath)
if err != nil {
log.Fatal(err)
}
defer new.Close()

//This will copy
bytesWritten, err := io.Copy(new, original)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Bytes Written: %d\n", bytesWritten)
}
 
reference:
io.copy

filepath

而立浦东