go 文件上传下载代码

https://blog.youkuaiyun.com/xmcy001122/article/details/104654096/

 

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
)

func upload(w http.ResponseWriter, req *http.Request) {
    contentType := req.Header.Get("content-type")
    contentLen := req.ContentLength

    fmt.Printf("upload content-type:%s,content-length:%d", contentType, contentLen)
    if !strings.Contains(contentType, "multipart/form-data") {
        w.Write([]byte("content-type must be multipart/form-data"))
        return
    }
    if contentLen >= 4*1024*1024 { // 10 MB
        w.Write([]byte("file to large,limit 4MB"))
        return
    }

    err := req.ParseMultipartForm(4 * 1024 * 1024)
    if err != nil {
        //http.Error(w, err.Error(), http.StatusInternalServerError)
        w.Write([]byte("ParseMultipartForm error:" + err.Error()))
        return
    }

    if len(req.MultipartForm.File) == 0 {
        w.Write([]byte("not have any file"))
        return
    }

    for name, files := range req.MultipartForm.File {
        fmt.Printf("req.MultipartForm.File,name=%s", name)

        if len(files) != 1 {
            w.Write([]byte("too many files"))
            return
        }
        if name == "" {
            w.Write([]byte("is not FileData"))
            return
        }

        for _, f := range files {
            handle, err := f.Open()
            if err != nil {
                w.Write([]byte(fmt.Sprintf("unknown error,fileName=%s,fileSize=%d,err:%s", f.Filename, f.Size, err.Error())))
                return
            }

            path := "./" + f.Filename
            dst, _ := os.Create(path)
            io.Copy(dst, handle)
            dst.Close()
            fmt.Printf("successful uploaded,fileName=%s,fileSize=%.2f MB,savePath=%s \n", f.Filename, float64(contentLen)/1024/1024, path)

            w.Write([]byte("successful,url=" + url.QueryEscape(f.Filename)))
        }
    }
}

func getContentType(fileName string) (extension, contentType string) {
    arr := strings.Split(fileName, ".")

    // see: https://tool.oschina.net/commons/
    if len(arr) >= 2 {
        extension = arr[len(arr)-1]
        switch extension {
        case "jpeg", "jpe", "jpg":
            contentType = "image/jpeg"
        case "png":
            contentType = "image/png"
        case "gif":
            contentType = "image/gif"
        case "mp4":
            contentType = "video/mpeg4"
        case "mp3":
            contentType = "audio/mp3"
        case "wav":
            contentType = "audio/wav"
        case "pdf":
            contentType = "application/pdf"
        case "doc", "":
            contentType = "application/msword"
        }
    }
    // .*( 二进制流,不知道下载文件类型)
    contentType = "application/octet-stream"
    return
}

func download(w http.ResponseWriter, req *http.Request) {
    if req.RequestURI == "/favicon.ico" {
        return
    }

    fmt.Printf("download url=%s \n", req.RequestURI)

    filename := req.RequestURI[1:]
    enEscapeUrl, err := url.QueryUnescape(filename)
    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    f, err := os.Open("./" + enEscapeUrl)
    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    info, err := f.Stat()
    if err != nil {
        w.Write([]byte(err.Error()))
        return
    }

    _, contentType := getContentType(filename)
    w.Header().Set("Content-Disposition", "attachment; filename="+filename)
    //w.Header().Set("Content-Type", http.DetectContentType(fileHeader))
    w.Header().Set("Content-Type", contentType)
    w.Header().Set("Content-Length", strconv.FormatInt(info.Size(), 10))

    f.Seek(0, 0)
    io.Copy(w, f)
}

func main() {
    fmt.Printf("linsten on :8080 \n")
    http.HandleFunc("/file/upload", upload)
    http.HandleFunc("/", download)
    http.ListenAndServe(":8080", nil)
}
 

### 回答1: 很高兴回答你的问题:Go 语言支持文件上传,你可以使用标准库中的 http 包中的 PostForm 函数来上传文件。示例代码如下:resp, err := http.PostForm("http://example.com/upload", url.Values{"key": {"value"}, "file": {open("/path/to/file")}}) ### 回答2: go语言实现文件上传代码可以使用gin框架来编写。 首先,我们需要导入gin框架的依赖包和其他必要的包: ```go import ( "github.com/gin-gonic/gin" "net/http" ) ``` 接下来,我们可以创建一个路由函数来处理文件上传的请求: ```go func uploadFile(c *gin.Context) { file, err := c.FormFile("file") // 获取文件信息 if err != nil { c.JSON(http.StatusBadRequest, gin.H{ "message": "文件上传失败", }) return } // 将文件保存到本地,可以根据需求修改存储路径 err = c.SaveUploadedFile(file, "./uploads/"+file.Filename) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ "message": "文件保存失败", }) return } c.JSON(http.StatusOK, gin.H{ "message": "文件上传成功", }) } ``` 然后,我们可以创建一个gin的路由器,并注册上传文件的路由: ```go func main() { r := gin.Default() r.POST("/upload", uploadFile) // 注册上传文件的路由 r.Run(":8080") // 启动服务 } ``` 最后,我们可以运行这个程序,并使用Postman或者其他工具发送一个POST请求,其中包含一个名为"file"的文件参数,即可实现文件上传的功能。 以上是用go语言实现文件上传代码,希望能对你有帮助。 ### 回答3: go语言文件上传代码如下: ```go package main import ( "fmt" "io" "log" "net/http" "os" ) func main() { http.HandleFunc("/upload", uploadFile) err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } func uploadFile(w http.ResponseWriter, req *http.Request) { // 获取上传的文件 file, handler, err := req.FormFile("file") if err != nil { fmt.Println("Error Retrieving the File") fmt.Println(err) return } defer file.Close() // 创建保存文件的目录 os.MkdirAll("./uploads", os.ModePerm) // 创建并打开新的文件 dst, err := os.Create("./uploads/" + handler.Filename) if err != nil { fmt.Println(err) return } defer dst.Close() // 将上传的文件内容复制到新的文件 _, err = io.Copy(dst, file) if err != nil { fmt.Println(err) return } // 成功保存文件 fmt.Fprintf(w, "File uploaded successfully") } ``` 通过以上代码,可以实现一个简单的文件上传服务。在`main`函数中,创建路由规则`/upload`来处理文件上传请求。在`uploadFile`函数中,通过`req.FormFile("file")`获取上传的文件,然后创建保存文件的目录并打开新的文件,最后将上传的文件内容复制到新的文件中。如果上传成功,返回`File uploaded successfully`,否则返回相应的错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值