使用Rest Controller Multipart File上传时损坏的图像

时间:2018-05-21 12:06:36

标签: java spring rest file-upload

当我尝试使用MultipartFile在我的RestController中上传图像时,有时它会创建一个损坏的图像(它不会打开,只是在文件中有一些垃圾)。它发生在我尝试快速发送(通过Postman)图像时。

这是我的控制器:

@PostMapping("/upload/photo")
public ResponseEntity<ServerResponse> uploadPhoto(@RequestParam MultipartFile file, HttpServletRequest httpServletRequest) {
    UserAccount userAccount = getPrincipal();
    String localAddress = "http://" + getServerUrl(httpServletRequest);      
    ServerResponse response = userAccountService.addPhoto(userAccount, file, localAddress);
    return getResponseEntity(response);
}

我的服务:

@Override
public ServerResponse<String> addPhoto(UserAccount userAccount, MultipartFile file, String localAddress) {
    String uploadFilePath = uploadFile(file);
    if(uploadFilePath.isEmpty()) {
        return new ServerResponse<>(ResponseStatus.BAD_REQUEST, "Please select a file to upload", "");
    }
    final String PHOTO_URL = localAddress + "/" + uploadFilePath;
    userAccount.setPhoto(PHOTO_URL);
    userAccountRepository.save(userAccount);
    return new ServerResponse<>(ResponseStatus.OK, null, PHOTO_URL);
}

private String uploadFile(MultipartFile file) {
    if (file.isEmpty()) {
        return "";
    }
    final String UPLOADED_FOLDER = "photos";
    String uniqueName = generateRandomString();
    String filePath = UPLOADED_FOLDER + "/" + uniqueName + file.getOriginalFilename();
    new File(UPLOADED_FOLDER).mkdirs();
    try {
        byte[] bytes = file.getBytes();
        Path path = Paths.get(filePath);
        if (Files.exists(path)){
            uniqueName = generateRandomString();
            filePath = UPLOADED_FOLDER + "/" + uniqueName + file.getOriginalFilename();
            path = Paths.get(filePath);
        }
        Files.write(path, bytes);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return filePath;
}

我也尝试将多部分文件读作InputStream,但没有帮助。

try (InputStream inputStream = file.getInputStream()) {
        Files.copy(inputStream, path,
                StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        e.printStackTrace();
    }    

我认为问题是,当我尝试在同一时间发送几个图像时它只是无法处理它?

0 个答案:

没有答案