關于文件上傳的支持,很多朋友詢問為何Ui界面不顯示上傳選擇頁面元素,而是輸入框,這里做一個統(tǒng)一的說明
在SwaggerBootstrapUi
以前的版本中(1.8.9之前),如果需要使用文件上傳,界面顯示,需要做如下代碼設置:
@ApiOperation(value = "多文件MultipartFile上傳")
@ApiImplicitParams({@ApiImplicitParam(name = "file[]", value = "文件流對象,接收數(shù)組格式", required = true,dataType = "MultipartFile",allowMultiple = true),
@ApiImplicitParam(name = "title", value = "title", required = true)}
)
@RequestMapping(value="/uploadMaterial",method = RequestMethod.POST)
@ResponseBody
public RestMessage uploadMaterial(@RequestParam(value="file[]",required = true) MultipartFile[] files,@RequestParam(value = "title") String title, HttpServletRequest request) throws IOException {
//int mul=1*1024*1024;
List<Map> uploadFiles= upload(request,files);
RestMessage rm=new RestMessage();
rm.setData(uploadFiles);
return rm;
}
需要指定dataType="MultipartFile"
,并且allowMultiple = true
必須設置,該屬性從字面意思能知道,允許多文件上傳,這里需要說明一下,因為在以前的版本作者并不知道文件的類型,所以特意強加了MultipartFile
類型,來達到Ui的線上顯示效果,所以單文件的上傳一直并未支持.
在1.9.0版本中,添加了對單文件上傳的支持,多文件上傳不需要多個input元素,開發(fā)者只需要按住Ctrl
鍵即可多選文件進行上傳,三種情況供大家參考使用:
這種類型在以前的版本中都支持,需要指定dataType="MultipartFile"
,并且allowMultiple = true
,示例代碼如下:
@ApiOperation(value = "多文件MultipartFile上傳")
@ApiImplicitParams({@ApiImplicitParam(name = "file[]", value = "文件流對象,接收數(shù)組格式", required = true,dataType = "MultipartFile",allowMultiple = true),
@ApiImplicitParam(name = "title", value = "title", required = true)}
)
@RequestMapping(value="/uploadMaterial",method = RequestMethod.POST)
@ResponseBody
public RestMessage uploadMaterial(@RequestParam(value="file[]",required = true) MultipartFile[] files,@RequestParam(value = "title") String title, HttpServletRequest request) throws IOException {
//more.....
}
在Ui的界面中,顯示效果如下:
除了dataType類型設置為MultipartFile
外,開發(fā)者還可以設置為__File
類型,代碼示例如下:
@ApiOperation(value = "多文件File上傳")
@ApiImplicitParams({@ApiImplicitParam(name = "file[]", value = "文件流對象,接收數(shù)組格式", required = true,dataType = "__File",allowMultiple = true),
@ApiImplicitParam(name = "title", value = "title", required = true)}
)
@RequestMapping(value="/uploadMaterial1",method = RequestMethod.POST)
@ResponseBody
public RestMessage uploadMaterial1(@RequestParam(value="file[]",required = true) MultipartFile[] files,@RequestParam(value = "title") String title, HttpServletRequest request) throws IOException {
//more....
}
和多文件File類型上傳類似,只需要去掉allowMultiple = true
屬性即可,代碼示例如下:
@ApiOperation(value = "單文件File上傳")
@ApiImplicitParams({@ApiImplicitParam(name = "file", value = "文件流對象,接收數(shù)組格式", required = true,dataType = "__File"),
@ApiImplicitParam(name = "title", value = "title", required = true)}
)
@RequestMapping(value="/uploadMaterial2",method = RequestMethod.POST)
@ResponseBody
public RestMessage uploadMaterial2(@RequestParam(value="file",required = true) MultipartFile file,@RequestParam(value = "title") String title, HttpServletRequest request) throws IOException {
//more...
}
以上三種情況示例可參考demo代碼UploadController.java
更多建議: