GolangNote

Golang笔记

golang 上传大文件并获取其大小的例子

Permalink

golang 上传大文件并获取其大小

Go: 上传大文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "os"
)

// 获取大小的借口
type Size interface {
    Size() int64
}

type Stat interface {
    Stat() (os.FileInfo, error)
}

// hello world, the web server
func HelloServer(w http.ResponseWriter, r *http.Request) {
    if "POST" == r.Method {
        r.ParseMultipartForm(32 << 20) // 32m
        file, _, err := r.FormFile("userfile")
        if err != nil {
            http.Error(w, err.Error(), 500)
            return
        }
        defer file.Close()
        f, err := os.Create("filenametosaveas")
        defer f.Close()
        io.Copy(f, file)

        // 获取文件信息的接口

        if statInterface, ok := file.(Stat); ok {
            fileInfo, _ := statInterface.Stat()
            fmt.Fprintf(w, "a上传文件的大小为: %d", fileInfo.Size())
        }
        if sizeInterface, ok := file.(Size); ok {
            fmt.Fprintf(w, "b上传文件的大小为: %d", sizeInterface.Size())
        }
        return
    }
    // 上传页面
    w.Header().Add("Content-Type", "text/html")
    w.WriteHeader(200)
    html := `
<form enctype="multipart/form-data" action="/hello" method="POST">
    Send this file: <input name="userfile" type="file" />
    <input type="submit" value="Send File" />
</form>
`
    io.WriteString(w, html)
}
func main() {
    http.HandleFunc("/hello", HelloServer)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

本文网址: https://golangnote.com/topic/121.html 转摘请注明来源

Related articles

Write a Comment to "golang 上传大文件并获取其大小的例子"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 5ms