golang 檔案上傳

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。最近再寫一個檔案上傳的功能,鑒於自己對go 語言的經驗不夠,所以寫的東西可能很一般,還請大家多多指教 <br/>話不多說,直接上代碼```package mainimport ("fmt""html/template""io""sync""log""net/http""os""time")type Buffer struct {bit []byteblen int}var bufpool *sync.Poolfunc initbt() {bufpool = &sync.Pool{}bufpool.New = func() interface{} {return Buffer{bit: make([]byte, 64*1024),blen: 0,}}}func Copy(dst1 io.Writer, src io.Reader, fd *os.File) (err error) {ta := time.Now().UnixNano()var cache chan *Buffer = make(chan *Buffer, 16*1024)var tb int64 = 0go func(fd1 *os.File) {for {select {case buf := <-cache:if buf == nil {goto end}nw1, ew := dst1.Write((*buf).bit[0:(*buf).blen])if ew != nil {err := ewfmt.Println("-----------", err)goto end}if (*buf).blen != nw1 {err := io.ErrShortWritefmt.Println(err)goto end}bufpool.Put((*buf))}}end:t2 := time.Now().UnixNano()fmt.Println("eg: ", t2-ta)fd1.Close()}(fd)for {buffer := bufpool.Get().(Buffer)nr, er := src.Read(buffer.bit)if er != nil {if er == io.EOF {close(cache)break}err = er}buffer.blen = nrcache <- &buffer}tb = time.Now().UnixNano()fmt.Println("read: ", tb-ta)return err}func upload(w http.ResponseWriter, r *http.Request) {r.ParseForm()if r.Method == "GET" {t, err := template.ParseFiles("upload.gptl")checkErr(err)t.Execute(w, nil)} else {file, handle, err := r.FormFile("file")checkErr(err)f, err := os.OpenFile("test/"+handle.Filename, os.O_WRONLY|os.O_CREATE, 0666)t1 := time.Now().UnixNano()Copy(f, file, f)checkErr(err)defer file.Close()t2 := time.Now().UnixNano()fmt.Printf("sum: %v\n", t2-t1)fmt.Fprintf(w, "upload over")}}func checkErr(err error) {if err != nil {err.Error()}}func main() {initbt()http.HandleFunc("/upload", upload)fmt.Println("open")err := http.ListenAndServe(":8888", nil)if err != nil {log.Fatal("listenAndServe: ", err)}}}```該檔案上傳中,主要是使用了 一個新的gorotine來執行檔案的寫操作,後通過chan 傳遞攜帶含有檔案資料的指標,<br/>自我感覺上傳效能提升了,還請各位 大神給出好的建議374 次點擊  ∙  1 贊  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.