文件上传下载

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); } }

原文发布于微信公众号 - Golang语言社区(Golangweb)

原文发表时间:2017-06-29

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

扫码关注云+社区

领取腾讯云代金券