无法使用 GOLANG 和 POLYMER http 将上传的文件保存在服务器上:没有这样的文件

2024-03-30

我正在使用 vaadin upload 通过聚合物在网络应用程序上上传文件。我使用 golang 作为后端。

<vaadin-upload target="../upload" max-files="20" accept="application/pdf,image/*" 
method="POST"> </vaadin-upload>

我检查了 vaadin 上传中使用的编码类型是多部分/表单数据。 我的 golang 代码如下。

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)
    }
}

它在服务器端给出错误http:没有这样的文件。我检查了当提供的文件字段名称不存在于请求中或不是文件字段时,FormFile 返回此错误。

How do I correct my form file name. Although everything seems fine on front-end enter image description here


做了一个快速测试,看来vaadin-upload uses file作为文件的表单数据参数名称。所以在行中

file, handler, err := r.FormFile("uploadFile")

replace uploadFile with file它应该有效。

It is 记录在 vaadin 主页上 https://vaadin.com/docs/-/part/elements/vaadin-upload/vaadin-upload-server.html that

为了支持同时上传,我们没有重复使用相同的 FormData 和 XMLHttpRequest,而是为每个文件创建一个新的。因此,服务器对于每个请求只考虑接收一个文件是可以的。

但是,我没有看到参数名称(file)记录下来,所以为了安全起见,你应该编写你的代码,这样它就不会使用该名称,即类似的东西

r.ParseMultipartForm(32 << 20)
m := r.MultipartForm
for _, v := range m.File {
    for _, f := range v {
        file, err := f.Open()
        if err != nil {
            fmt.Println(err)
            return
        }
        defer file.Close()
        // do something with the file data
        ...
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

无法使用 GOLANG 和 POLYMER http 将上传的文件保存在服务器上:没有这样的文件 的相关文章

随机推荐