使用Swagger直接上傳文件的方法
經(jīng)常使用swagger,可以通過設(shè)置[ProducesResponseType]
標(biāo)記接口的返回信息;swagger也能通過接口的參數(shù)列表,自動(dòng)獲得發(fā)送的數(shù)據(jù)結(jié)構(gòu)信息。
不過有一個(gè)例外,就是上傳文件的時(shí)候,設(shè)置了[Consumes]的內(nèi)容為multi-part/form-data
,但是swagger并不能正常感知是上傳文件的。代碼是這個(gè)樣子的:
關(guān)于文件上傳的細(xì)節(jié),可以看多年前我寫過一篇有關(guān)通過WEBAPI上傳文件的文章。
[Consumes("multipart/form-data")] [ODataRoute] [HttpPost] public async Task<ActionResult> Post(IFormCollection collection) { var file = collection.Files[0]; if(file != null) { var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + file.FileName; var path = Path.Combine(_webHostEnvironment.WebRootPath, "Files", filename); using FileStream fileStream = new FileStream(path, FileMode.Create); await file.CopyToAsync(fileStream); var uri = "Files/" + filename; var fileEntity = new Models.File { Url = uri, LastModified = DateTime.Now }; _homeworkDataContext.Files.Add(fileEntity); await _homeworkDataContext.SaveChangesAsync(); return Created(WebUtility.UrlEncode(uri), fileEntity); } return BadRequest(); }
實(shí)際上,swagger一直提示,上傳的內(nèi)容是一個(gè)array類型,當(dāng)然API是沒有問題的,可以通過POSTMAN進(jìn)行發(fā)送,不過不能在網(wǎng)頁上直接操作,總覺得心里有點(diǎn)不太舒服。
方法
搜索了一下辦法,比較靠譜的,就是通過增加一個(gè)IOperationFilter
來實(shí)現(xiàn)目的。
// CODE FROM https://www.talkingdotnet.com/how-to-upload-file-via-swagger-in-asp-net-core-web-api/ public class FileUploadOperation : IOperationFilter { public void Apply(Operation operation, OperationFilterContext context) { if (operation.OperationId.ToLower() == "apivaluesuploadpost") { operation.Parameters.Clear(); operation.Parameters.Add(new NonBodyParameter { Name = "uploadedFile", In = "formData", Description = "Upload File", Required = true, Type = "file" }); operation.Consumes.Add("multipart/form-data"); } } }
然后,在services.ConfigureSwaggerGen()
參數(shù)中,添加
options.OperationFilter<FileUploadOperation>();
方法的原理是通過重寫操作某個(gè)特定API的的過濾器,來實(shí)現(xiàn)對(duì)返回內(nèi)容的操作。
此方法適用于OAS2,實(shí)質(zhì)上是實(shí)現(xiàn)了這里的規(guī)范要求。
我已經(jīng)用上.NET 5.0了,自帶了swagger都支持的是OpenAPI 3,這個(gè)方法不好用了。不過思想應(yīng)該相同,首先看看OpenAPI 3的規(guī)范,文件上傳需要定義為:
requestBody: content: multipart/form-data: schema: type: object properties: fileName: type: string format: binary
這個(gè)套路和OpenAPI 2完全不一樣,需要重新設(shè)置requestBody才行。我們按照要求改造代碼。
public class FileUploadOperation : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { //判斷上傳文件的類型,只有上傳的類型是IFormCollection的才進(jìn)行重寫。 if (context.ApiDescription.ActionDescriptor.Parameters.Any(w => w.ParameterType == typeof(IFormCollection))) { Dictionary<string, OpenApiSchema> schema = new Dictionary<string, OpenApiSchema>(); schema["fileName"] = new OpenApiSchema { Description = "Select file", Type = "string", Format = "binary" }; Dictionary<string, OpenApiMediaType> content = new Dictionary<string, OpenApiMediaType>(); content["multipart/form-data"] = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object", Properties = schema } }; operation.RequestBody = new OpenApiRequestBody() { Content = content }; } } }
執(zhí)行之后,swagger已經(jīng)可以正常識(shí)別了,通過選擇文件即可上傳,效果如下:
參考資料
https://docs.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-5.0
https://www.talkingdotnet.com/how-to-upload-file-via-swagger-in-asp-net-core-web-api/
到此這篇關(guān)于使用Swagger直接上傳文件的方法的文章就介紹到這了,更多相關(guān)Swagger上傳文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java開發(fā)ExecutorService監(jiān)控實(shí)現(xiàn)示例詳解
這篇文章主要為大家介紹了java開發(fā)ExecutorService監(jiān)控實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07SpringBoot實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源切換的方法總結(jié)
項(xiàng)目開發(fā)中經(jīng)常會(huì)遇到多數(shù)據(jù)源同時(shí)使用的場(chǎng)景,比如冷熱數(shù)據(jù)的查詢等情況,所以接下來本文就來介紹一下如何使用實(shí)現(xiàn)自定義注解的形式來實(shí)現(xiàn)動(dòng)態(tài)數(shù)據(jù)源切換吧2023-12-12JAVA中StackOverflowError錯(cuò)誤的解決
這篇文章主要介紹了JAVA中StackOverflowError錯(cuò)誤的解決,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04