前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >文件上传下载

文件上传下载

作者头像
李海彬
发布2018-03-27 11:48:04
1.2K0
发布2018-03-27 11:48:04
举报
文章被收录于专栏:Golang语言社区
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); } }
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2017-06-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Golang语言社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档