我正在使用 vaadin upload 上传带有聚合物的 Web 应用程序上的文件。我使用 golang 作为后端。
<vaadin-upload target="../upload" max-files="20" accept="application/pdf,image/*"
method="POST"> </vaadin-upload>
Run Code Online (Sandbox Code Playgroud)
我检查了 vaadin 上传中使用的编码类型是multipart/form-data。我的 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)
}
}
Run Code Online (Sandbox Code Playgroud)
它在服务器端http: no such file上给出错误。当提供的文件字段名称不存在于请求中或文件字段中时,我检查了此错误是否由 FormFile 返回。
为面临同样问题的人回答我自己的问题。发现一些代码可以在不知道键值的情况下访问文件。
func UploadHandler(res http.ResponseWriter, req *http.Request) {
var (
status int
err error
)
defer func() {
if nil != err {
http.Error(res, err.Error(), status)
}
}()
// parse request
// const _24K = (1 << 20) * 24
if err = req.ParseMultipartForm(32 << 20); nil != err {
status = http.StatusInternalServerError
return
}
fmt.Println("No memory problem")
for _, fheaders := range req.MultipartForm.File {
for _, hdr := range fheaders {
// open uploaded
var infile multipart.File
if infile, err = hdr.Open(); nil != err {
status = http.StatusInternalServerError
return
}
// open destination
var outfile *os.File
if outfile, err = os.Create("./uploaded/" + hdr.Filename); nil != err {
status = http.StatusInternalServerError
return
}
// 32K buffer copy
var written int64
if written, err = io.Copy(outfile, infile); nil != err {
status = http.StatusInternalServerError
return
}
res.Write([]byte("uploaded file:" + hdr.Filename + ";length:" + strconv.Itoa(int(written))))
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5643 次 |
| 最近记录: |