mirror of
https://github.com/gin-gonic/gin.git
synced 2026-11-19 16:57:22 +08:00
fix(binding): leave file fields unset for an empty multipart file part
Browsers send a file input with no file selected as a part with filename="" and an empty body. mime/multipart stores that part as a form value, so multipartRequest.TrySet found no files and fell back to setByForm, which bound a non-nil empty multipart.FileHeader to pointer fields and one empty entry to slices and arrays. binding:"required" then passed although no file was uploaded. Leave file-typed fields unset when the request has no files for the key, so an empty file part binds like a missing one. Fixes #2376
This commit is contained in:
parent
0f09c3a9b4
commit
fc07a2296b
@ -28,6 +28,9 @@ func (r *multipartRequest) TrySet(value reflect.Value, field reflect.StructField
|
||||
if files := r.MultipartForm.File[key]; len(files) != 0 {
|
||||
return setByMultipartFormFile(value, field, files)
|
||||
}
|
||||
if isFileHeaderType(value.Type()) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
return setByForm(value, field, r.MultipartForm.Value, key, opt)
|
||||
}
|
||||
@ -72,3 +75,15 @@ func setArrayOfMultipartFormFiles(value reflect.Value, field reflect.StructField
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
var fileHeaderType = reflect.TypeOf(multipart.FileHeader{})
|
||||
|
||||
func isFileHeaderType(t reflect.Type) bool {
|
||||
if t.Kind() == reflect.Slice || t.Kind() == reflect.Array {
|
||||
t = t.Elem()
|
||||
}
|
||||
if t.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
}
|
||||
return t == fileHeaderType
|
||||
}
|
||||
|
||||
@ -69,6 +69,31 @@ func TestFormMultipartBindingBindTwoFiles(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormMultipartBindingBindEmptyFile(t *testing.T) {
|
||||
var s struct {
|
||||
FilePtr *multipart.FileHeader `form:"file"`
|
||||
SliceValues []multipart.FileHeader `form:"file"`
|
||||
SlicePtrs []*multipart.FileHeader `form:"file"`
|
||||
ArrayPtrs [1]*multipart.FileHeader `form:"file"`
|
||||
}
|
||||
req := createRequestMultipartFiles(t, testFile{"file", "", nil})
|
||||
err := FormMultipart.Bind(req, &s)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Nil(t, s.FilePtr)
|
||||
assert.Nil(t, s.SliceValues)
|
||||
assert.Nil(t, s.SlicePtrs)
|
||||
assert.Nil(t, s.ArrayPtrs[0])
|
||||
|
||||
var required struct {
|
||||
File *multipart.FileHeader `form:"file" binding:"required"`
|
||||
}
|
||||
req = createRequestMultipartFiles(t, testFile{"file", "", nil})
|
||||
err = FormMultipart.Bind(req, &required)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, required.File)
|
||||
}
|
||||
|
||||
func TestFormMultipartBindingBindError(t *testing.T) {
|
||||
files := []testFile{
|
||||
{"file", "file1", []byte("hello")},
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user