swagger-无法识别的响应类型;将内容显示为文本

e0bqpujr  于 2022-12-23  发布在  其他
关注(0)|答案(4)|浏览(620)

我用swagger-ui-express模块为我的节点js后端构建了一个swagger,我有一个返回文件(pdf-doc或xlsx)的端点,当我在swagger上测试我的端点时,它返回了我200个响应,并且在body上总是显示“无法识别的响应类型”的消息;将内容显示为文本这是我的swagger端点的代码。

"/reports?typeDoc={typeDoc}&file={file}": {
            "get": {
                "tags": [
                    "Generate report"
                ],
                "description": "",
                "operationId": "",
                "parameters": [
                    {
                        "name": "typeDoc",
                        "in": "path",
                        "description": "type of document",
                        "required": true,
                        "type": "string"
                    },
                    {
                        "name": "file",
                        "in": "path",
                        "description": "name of the file",
                        "required": true,
                        "type": "string"
                    }
                ],
                "responses": {
                    "200":{
                    "description": "Report generated succefully. ",
                    "content":{
                        "application/octet-stream":{
                            "schema":{
                                "type": "string",
                                "format": "binary"}
                        }
                    }
                    },
                    "500": {
                        "description": "Error in zip file structure or typeDoc"
                    }
                }
            }   
    }
0ve6wy6x

0ve6wy6x1#

尝试添加如下标题

content-disposition: attachment; filename = test.xlsx
content-type: multipart / form-data

并且Swagger-UI将理解响应类型并提供下载文件。

62lalag4

62lalag42#

Swagger UI对此有一个open issue。作为一种解决方案,添加标头(“filename”指令可以省略)

content-disposition: attachment; filename="<some file name>"

然后,Swagger UI将为响应正文提供“下载文件”链接。

注意:content-type头应该被设置为响应的实际内容类型(并且它将在打开下载链接时被浏览器解释);通常,响应的内容类型不应是另一个答案所建议的“multipart/form”。

yzckvree

yzckvree3#

您可以尝试使用octet-stream作为后备。标题应如下所示:

content-disposition: inline; filename=sample.pdf 
content-type: application/octet-stream
efzxgjgh

efzxgjgh4#

对于使用FileContentResultFileStreamResult的任何人,请确保已设置“FileDownloadName”属性。
文件内容结果:

var result = new FileContentResult(reader.BaseStream.ReadToEnd(),MediaTypeNames.Application.Pdf);
result.FileDownloadName = "JEfTest.pdf";

文件流结果:

var result = new FileStreamResult(stream, MediaTypeNames.Application.Pdf);
result.FileDownloadName = "JEfTest.pdf";

相关问题