英文:
Pass filename of the file selected for upload using enctype="multipart/form-data" to a struct field in Golang
问题
我的应用程序使用HTML代码片段来上传文件的表单。
<form method="POST" action="/addproduct" enctype="multipart/form-data">
<label class="form-control-label" for="productimage"></label>
{{with .Errors.image}}
<div class="alert alert-danger">
{{.}}
</div>
{{end}}
<input type="file" name="productimage" id="productimage" multiple="multiple" class="btn btn-danger">
<input type="submit" name="submit" value="Submit" class="btn btn-info">
</form>
我需要获取上传文件的文件名,并将其传递给Golang中的结构字段。
file, header, err := r.FormFile("productimage")
defer file.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
var pimage = header.Filename
p := &Product{
Puid: Puid(),
Pname: r.FormValue("productName"),
Quantity: r.FormValue("quantity"),
Price: r.FormValue("price"),
Image: pimage,
}
我正在尝试将所选文件的名称传递给结构体Product
的image
字段。有关如何完成此操作的建议吗?
英文:
My application uses the html code snippet for the form to upload a file
<form method="POST" action="/addproduct" enctype="multipart/form-data">
<label class="form-control-label" for="productimage"></label>
{{with .Errors.image}}
<div class="alert alert-danger">
{{.}}
</div>
{{end}}
<input type="file" name="productimage" id = "productimage" multiple="multiple" class = "btn btn-danger">
<input type="submit" name="submit" value="Submit" class = "btn btn-info">
</form>
I need to grab the filename of the uploaded file and pass it to a struct field in Golang.
file, header, err := r.FormFile("productimage")
defer file.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
var pimage = header.Filename
p := &Product{
Puid: Puid(),
Pname: r.FormValue("productName"),
Quantity: r.FormValue("quantity"),
Price: r.FormValue("price"),
Image: pimage,
}
I am trying to pass the name of the file selected for uploaded to 'image' field of the struct 'Product'. Any suggestions on how this can be done?
答案1
得分: 0
你可以尝试使用以下代码替代r.FormFile()
的调用:
mpr, _ := r.MultipartReader()
filePart, _ := r.NextPart()
fileName := filePart.FileName()
不过,我建议你检查错误情况
英文:
Instead of calling r.FormFile()
, you could instead try:
mpr, _ := r.MultipartReader()
filePart, _ := r.NextPart()
fileName := filePart.FileName()
However, I would check the errors
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论