56. 上传文件(CS版)

作者: 厚土火焱 | 来源:发表于2017-09-18 00:41 被阅读163次

    这个版本的上传文件是服务端和客户端是分离的。
    也在单机上做了大文件测试。测通。
    因为走的还是表单提交的模式。所以客户端收不到文件传递的结果。这个还需要抽时间改进。
    服务端的根上要建立 upload 和 staticfile 路径。不然会影响文件上传。
    服务端代码示例

    /**
    * MyFileUpload02
    * @Author:  Jian Junbo
    * @Email:   junbojian@qq.com
    * @Create:  2017/9/17 16:30
    * Copyright (c) 2017 Jian Junbo All rights reserved.
    *
    * Description:  
    */
    package main
    
    import (
        "io"
        "net/http"
        "os"
        "log"
        "time"
        "strconv"
        "path"
    )
    
    func uploadHandler(w http.ResponseWriter, r *http.Request) {
        switch r.Method {
        //POST takes the uploaded file(s) and saves it to disk.
        case "POST":
            //parse the multipart form in the request
            err := r.ParseMultipartForm(100000)
            if err != nil {
                http.Error(w, err.Error(), http.StatusInternalServerError)
                return
            }
    
            //get a ref to the parsed multipart form
            m := r.MultipartForm
    
            //get the *fileheaders
            files := m.File["uploadfile"]
            for i, _ := range files {
                //save file as filename
                filename := string(time.Now().Format("20060102150405")) + strconv.Itoa(time.Now().Nanosecond()) + path.Ext(files[i].Filename)
    
                //for each fileheader, get a handle to the actual file
                file, err := files[i].Open()
                defer file.Close()
                if err != nil {
                    http.Error(w, err.Error(), http.StatusInternalServerError)
                    return
                }
                //create destination file making sure the path is writeable.
                dst, err := os.Create("./upload/" + filename)
                defer dst.Close()
                if err != nil {
                    http.Error(w, err.Error(), http.StatusInternalServerError)
                    return
                }
                //copy the uploaded file to the destination file
                if _, err := io.Copy(dst, file); err != nil {
                    http.Error(w, err.Error(), http.StatusInternalServerError)
                    return
                }
                //fmt.Fprintln(w, dst.Name())
                log.Println(dst.Name())
            }
    
        default:
            w.WriteHeader(http.StatusMethodNotAllowed)
        }
    }
    
    func main() {
        http.HandleFunc("/upload", uploadHandler)
    
        //static file handler.
        http.Handle("/staticfile/", http.StripPrefix("/staticfile/", http.FileServer(http.Dir("./staticfile"))))
    
        //Listen on port 8080
        http.ListenAndServe(":8080", nil)
    }
    
    

    客户端代码示例

    /**
    * MyFileUpload02Client
    * @Author:  Jian Junbo
    * @Email:   junbojian@qq.com
    * @Create:  2017/9/17 21:34
    * Copyright (c) 2017 Jian Junbo All rights reserved.
    *
    * Description:  上传文件客户端
    */
    package main
    
    import (
        "bytes"
        "mime/multipart"
        "log"
        "os"
        "io"
        "net/http"
    )
    
    func main() {
        //创建一个表单
        server := "http://localhost:8080/upload"
        myfile := "F:\\Temp\\qwqwqw.mp4"
        buf := new(bytes.Buffer)
        writer := multipart.NewWriter(buf)
        formFile, err := writer.CreateFormFile("uploadfile", myfile)
        if err != nil{
            log.Fatal("Create form file failed: %s\n", err)
        }
    
        //从文件读取数据,写入表单
        srcFile, err := os.Open(myfile)
        if err != nil{
            log.Fatal("Open source file failed: %s\n", err)
        }
        defer srcFile.Close()
        _, err = io.Copy(formFile, srcFile)
        if err != nil{
            log.Fatal("Write to formfile failed: %s\n", err)
        }
    
        //发送表单
        contentType := writer.FormDataContentType()
        writer.Close()  //发送之前必须调用close(),以便写入文件结尾行
        _, err = http.Post(server, contentType, buf)
        if err != nil{
            log.Fatal("Post failed: %s\n", err)
        }
    }
    
    

    相关文章

      网友评论

      本文标题:56. 上传文件(CS版)

      本文链接:https://www.haomeiwen.com/subject/eikvsxtx.html