package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"io"
"crypto/md5"
"time"
"strconv"
"archive/zip"
)
var buf []byte
func sayhelloName(w http.ResponseWriter, r *http.Request){
/*if r.Method == "Get" {
t,_:=template.ParseFiles("index.html")
t.Execute(w,nil)
}else {
fmt.Println("...")
}
*/
t,_:=template.ParseFiles("index.html")
t.Execute(w,nil)
fmt.Println("..")
}
func upload(w http.ResponseWriter, r* http.Request){
fmt.Println("method:", r.Method)
if r.Method == "GET" {
crutime := time.Now().Unix()
h := md5.New()
io.WriteString(h,strconv.FormatInt(crutime, 10))
token := fmt.Sprintf("%x",h.Sum(nil))
t, _ := template.ParseFiles("upload.html")
t.Execute(w,token)
}else {
r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
fmt.Fprintf(w, "%v",handler.Header)
f, err := os.OpenFile("./test/" + handler.Filename,os.O_WRONLY|os.O_CREATE, 066)
if err != nil {
fmt.Println(err)
return
}
defer f.Close()
io.Copy(f, file)
}
}
func download(rw http.ResponseWriter, r* http.Request){
zipName:="ZipTest.zip"
rw.Header().Set("Content-Type","application/zip")
rw.Header().Set("Content-Disposition",fmt.Sprintf("attachment; filename=\"%s\"",zipName))
err := getZip(rw)
if err != nil {
log.Fatal(err)
}
}
func getZip(w io.Writer) error {
zipW := zip.NewWriter(w)
defer zipW.Close()
for i := 0; i< 5; i++ {
f, err := zipW.Create(strconv.Itoa(i) + ".txt")
if err != nil {
return err
}
_, err = f.Write([]byte(fmt.Sprintf("Hello file %d", i)))
if err != nil {
return err
}
}
return nil
}
func downfile(rw http.ResponseWriter, r* http.Request){
fileName := "1.txt"
file, err := os.Open(fileName);
if err != nil {
fmt.Fprintf(os.Stderr,"%v\n",err)
}
defer file.Close()
rw.Header().Set("Content-Disposition","attachment; filename=1.txt")
rw.Header().Set("Content-Type",r.Header.Get("Content-Type"))
io.Copy(rw,file)
}
func main(){
http.HandleFunc("/",sayhelloName)
http.HandleFunc("/upload",upload)
http.HandleFunc("/download",download)
http.HandleFunc("/downfile",downfile)
err := http.ListenAndServe(":9090",nil)
if err != nil {
log.Fatal("ListenAndServe: ",err);
}
}
有疑问加站长微信联系(非本文作者)