在使用SwaggerBootstrapUi的朋友经常询问的一个问题,为什么上传参数file对象不显示file文本域,而是普通文本,如下图:

    文件上传不显示上传选择文本域 - 图1

    因为Springfox-Swagger针对不同的版本,某些版本也会出现此问题,为一劳永逸,SwaggerBootstrapUi特别指定需要强指定dataType类型为MultipartFile

    代码示例(UploadController.java):

    1. @ApiOperation(value = "文件素材上传接口")
    2. @ApiImplicitParams({@ApiImplicitParam(name = "file[]", value = "文件流对象,接收数组格式", required = true,dataType = "MultipartFile",allowMultiple = true),
    3. @ApiImplicitParam(name = "title", value = "title", required = true)}
    4. )
    5. @RequestMapping(value="/uploadMaterial",method = RequestMethod.POST)
    6. @ResponseBody
    7. public RestMessage uploadMaterial(@RequestParam(value="file[]",required = true) MultipartFile[] files,@RequestParam(value = "title") String title, HttpServletRequest request) throws IOException {
    8. //int mul=1*1024*1024;
    9. String realPath=request.getSession().getServletContext().getRealPath("/upload");
    10. File realFile=new File(realPath);
    11. if (!realFile.exists()){
    12. realFile.mkdirs();
    13. }
    14. List<Map> uploadFiles= Lists.newArrayList();
    15. System.out.println("进入图片上传接口:"+files.length +"张");
    16. for (MultipartFile file : files) {
    17. File targetFile=new File(realFile,file.getOriginalFilename());
    18. FileOutputStream fileOutputStream=null;
    19. InputStream ins=null;
    20. try{
    21. fileOutputStream=new FileOutputStream(targetFile);
    22. int i=-1;
    23. byte[] bytes=new byte[1024*1024];
    24. ins=file.getInputStream();
    25. while ((i=ins.read(bytes))!=-1){
    26. fileOutputStream.write(bytes,0,i);
    27. }
    28. }catch (IOException e){
    29. }finally {
    30. closeQuilty(ins);
    31. closeQuilty(fileOutputStream);
    32. }
    33. Map fileInfo= Maps.newHashMap();
    34. fileInfo.put("id", UUID.randomUUID().toString());
    35. fileInfo.put("url",targetFile.getPath());
    36. fileInfo.put("original_name",targetFile.getName());
    37. uploadFiles.add(fileInfo);
    38. }
    39. RestMessage rm=new RestMessage();
    40. rm.setData(uploadFiles);
    41. return rm;
    42. }

    关于多文件上传,设置allowMultiple=true即可,在UI界面端,按住Ctrl键即可多选文件.