1 回答
TA贡献1785条经验 获得超4个赞
好吧,我终于明白了它是如何multipart.Reader工作的,并且想出了一个解决方案。
首先让我们澄清一下,与 Goa 通常的工作方式不同(“自动”映射请求参数与字段Payload),MultipartRequest()我必须自己进行映射,因此Payload实际上可以具有任何结构。
就我而言,我重新定义了我的Payload结构,如下所示:
// ImageUpload single image upload element
var ImageUpload = Type("ImageUpload", func() {
Description("A single Image Upload type")
Attribute("type", String)
Attribute("bytes", Bytes)
Attribute("name", String)
})
// ImageUploadPayload is a list of files
var ImageUploadPayload = Type("ImageUploadPayload", func() {
Description("Image Upload Payload")
Attribute("Files", ArrayOf(ImageUpload), "Collection of uploaded files")
})
简而言之,我想支持上传多个文件,每个文件都有其 mime 类型、文件名和数据。
为了实现这一点,我实现了multipart.go如下解码器功能:
func ImagesUploadDecoderFunc(mr *multipart.Reader, p **images.ImageUploadPayload) error {
res := images.ImageUploadPayload{}
for {
p, err := mr.NextPart()
if err == io.EOF {
break
}
if err != nil {
fmt.Fprintln(os.Stderr, err)
return err
}
_, params, err := mime.ParseMediaType(p.Header.Get("Content-Disposition"))
if err != nil {
// can't process this entry, it probably isn't an image
continue
}
disposition, _, err := mime.ParseMediaType(p.Header.Get("Content-Type"))
// the disposition can be, for example 'image/jpeg' or 'video/mp4'
// I want to support only image files!
if err != nil || !strings.HasPrefix(disposition, "image/") {
// can't process this entry, it probably isn't an image
continue
}
if params["name"] == "file" {
bytes, err := ioutil.ReadAll(p)
if err != nil {
// can't process this entry, for some reason
fmt.Fprintln(os.Stderr, err)
continue
}
filename := params["filename"]
imageUpload := images.ImageUpload{
Type: &disposition,
Bytes: bytes,
Name: &filename,
}
res.Files = append(res.Files, &imageUpload)
}
}
*p = &res
return nil
}
- 1 回答
- 0 关注
- 114 浏览
添加回答
举报