1 回答

TA貢獻(xiàn)1785條經(jīng)驗 獲得超4個贊
好吧,我終于明白了它是如何multipart.Reader工作的,并且想出了一個解決方案。
首先讓我們澄清一下,與 Goa 通常的工作方式不同(“自動”映射請求參數(shù)與字段Payload),MultipartRequest()我必須自己進(jìn)行映射,因此Payload實際上可以具有任何結(jié)構(gòu)。
就我而言,我重新定義了我的Payload結(jié)構(gòu),如下所示:
// 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 類型、文件名和數(shù)據(jù)。
為了實現(xiàn)這一點,我實現(xiàn)了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 關(guān)注
- 171 瀏覽
添加回答
舉報