尝试上传文件,数组遇到困难

时间:2019-05-08 07:20:52

标签: java spring spring-boot arraylist multipart

我正在尝试上传文件,但是Multipartfiles不能正确传递。

这是我要添加一些文件的控制器。仅返回@ RequestParam,Arrays.asList(files)返回一个空数组。我将在下面添加打印行的结果。

@Transactional
    @RequestMapping(path = "/profile/files", method=RequestMethod.POST)
    @ApiResponses(value = {
            @ApiResponse(code = HttpServletResponse.SC_BAD_REQUEST, message = "Wrong file type", response = ErrorResponse.class),
            @ApiResponse(code = HttpServletResponse.SC_FORBIDDEN, message = "Not authorized", response = ErrorResponse.class),
            @ApiResponse(code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message = "Internal Error", response = InternalErrorResponse.class)
    })
    @ResponseBody
    @ApiOperation(
            value = "Add files",
            tags = "Users"
    )
    public List<FileDto> addProfilePicture(@RequestParam("file") MultipartFile[] files) {
        System.out.println("Controller: Files from params: " + files.toString());
        List<MultipartFile> filesToAdd = Arrays.asList(files);
        System.out.println("Controller: Files Array.asList: " + filesToAdd);
        List<File> savedFiles = userService.addFiles(filesToAdd);
        System.out.println("Controller: Files returned from addFiles(): " + savedFiles);
        return savedFiles.stream().map(FileDto::new).collect(Collectors.toList());
    }

这是服务部分:

public List<File> addFiles(List<MultipartFile> files) {

        System.out.println("Service: Input files: " + files);

        List<File> savedFiles = new ArrayList<>();

        for(MultipartFile file: files){
            File savedFile = fileService.save(file, FileService.LOCATION_DOCUMENT_FILE, S3Adapter.ACL_OWNER_ONLY);
            savedFiles.add(savedFile);
        }
        System.out.println("Service: Saved files: " + savedFiles);
        return savedFiles;
    }

这是尝试通过邮递员上传图像时打印线为我产生的结果:

Controller: Files from params: [Lorg.springframework.web.multipart.MultipartFile;@794108b7
Controller: Files Array.asList: []
Service: Input files: []
Service: Saved files: []
Controller: Files returned from addFiles(): []

1 个答案:

答案 0 :(得分:3)

从POSTMAN上传时,您似乎正在使用binary选项。仅当您以HttpServletRequest / MultipartRequest的身份接收时,此选项才有效。

要以@RequestParam("files")的格式接收文件,您需要使用form-data选项,并将密钥指定为files,并从下拉列表中选择file作为值,选择多个文件,然后提交请求。它将正常工作。

Screen Shot for your reference