go处理文件上传

你想处理一个由用户上传的文件,比如你正在建设一个类似Instagram的网站,你需要存储用户拍摄的照片。这种需求该如何实现呢?

要使表单能够上传文件,首先第一步就是要添加form的enctype属性,enctype属性有如下三种情况:

application/x-www-form-urlencoded   表示在发送前编码所有字符(默认)
multipart/form-data   不对字符编码。在使用包含文件上传控件的表单时,必须使用该值。
text/plain    空格转换为 "+" 加号,但不对特殊字符编码。

所以,表单的html代码应该类似于:

<html>
<head>
    <title>上传文件</title>
</head>
<body>
<form enctype="multipart/form-data" action="http://127.0.0.1:9090/upload" method="post">
  <input type="file" name="uploadfile" />
  <input type="hidden" name="token" value="{{.}}"/>
  <input type="submit" value="upload" />
</form>
</body>
</html>

在服务器端,我们增加一个handlerFunc:

http.HandleFunc("/upload", upload)

// 处理/upload 逻辑
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.gtpl")
        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, 0666)
        if err != nil {
            fmt.Println(err)
            return
        }
        defer f.Close()
        io.Copy(f, file)
    }
}

通过上面的代码可以看到,处理文件上传我们需要调用r.ParseMultipartForm,里面的参数表示maxMemory,调用ParseMultipartForm之后,上传的文件存储在maxMemory大小的内存里面,如果文件大小超过了maxMemory,那么剩下的部分将存储在系统的临时文件中。我们可以通过r.FormFile获取上面的文件句柄,然后实例中使用了io.Copy来存储文件。

获取其他非文件字段信息的时候就不需要调用r.ParseForm,因为在需要的时候Go自动会去调用。而且ParseMultipartForm调用一次之后,后面再次调用不会再有效果。

通过上面的实例我们可以看到我们上传文件主要三步处理:

  1. 表单中增加enctype="multipart/form-data"
  2. 服务端调用r.ParseMultipartForm,把上传的文件存储在内存和临时文件中
  3. 使用r.FormFile获取文件句柄,然后对文件进行存储等处理。

文件handler是multipart.FileHeader,里面存储了如下结构信息

type FileHeader struct {
    Filename string
    Header   textproto.MIMEHeader
    // contains filtered or unexported fields
}

 

客户端上传文件

我们上面的例子演示了如何通过表单上传文件,然后在服务器端处理文件,其实Go支持模拟客户端表单功能支持文件上传,详细用法请看如下示例:

package main

import (
    "bytes"
    "fmt"
    "io"
    "io/ioutil"
    "mime/multipart"
    "net/http"
    "os"
)

func postFile(filename string, targetUrl string) error {
    bodyBuf := &bytes.Buffer{}
    bodyWriter := multipart.NewWriter(bodyBuf)

    //关键的一步操作
    fileWriter, err := bodyWriter.CreateFormFile("uploadfile", filename)
    if err != nil {
        fmt.Println("error writing to buffer")
        return err
    }

    //打开文件句柄操作
    fh, err := os.Open(filename)
    if err != nil {
        fmt.Println("error opening file")
        return err
    }
    defer fh.Close()

    //iocopy
    _, err = io.Copy(fileWriter, fh)
    if err != nil {
        return err
    }

    contentType := bodyWriter.FormDataContentType()
    bodyWriter.Close()

    resp, err := http.Post(targetUrl, contentType, bodyBuf)
    if err != nil {
        return err
    }
    defer resp.Body.Close()
    resp_body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        return err
    }
    fmt.Println(resp.Status)
    fmt.Println(string(resp_body))
    return nil
}

// sample usage
func main() {
    target_url := "http://localhost:9090/upload"
    filename := "./astaxie.pdf"
    postFile(filename, target_url)
}

上面的例子详细展示了客户端如何向服务器上传一个文件的例子,客户端通过multipart.Write把文件的文本流写入一个缓存中,然后调用http的Post方法把缓存传到服务器。

如果你还有其他普通字段例如username之类的需要同时写入,那么可以调用multipart的WriteField方法写很多其他类似的字段。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
### 回答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`,否则返回相应的错误信息。
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值