Я не могу понять, как загрузить файл jpg с помощью mockMvc со споком. Когда я выполняю запрос вручную с почтальоном, все работает нормально, и изображения загружаются. Я использую весеннюю загрузку
Вот контроллер:
@PostMapping(value = "/items/{id}/images")
public ResponseEntity<?> uploadImage(@PathVariable Long id, @RequestParam("file") MultipartFile file,
UriComponentsBuilder ucb) {
if (file.isEmpty()) throw new IllegalArgumentException("File is empty");
Optional<Image> image = itemService.addImageToItem(id, file);
if (!image.isPresent()) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Unable to upload image");
}
URI location = ucb.path("/items/")
.path(String.valueOf(id))
.path("/images/")
.path(image.get().getId().toString()).build().toUri();
return ResponseEntity.created(location).contentType(MediaType.APPLICATION_JSON).body(image.get());
}
и вот тест:
@SpringBootTest
@AutoConfigureMockMvc
class FileUploadTest extends Specification {
@Autowired
MockMvc mockMvc;
@Shared
MockMultipartFile multiPartImage;
@Shared byte[] content = null;
def setupSpec() {
Path path = new ClassPathResource("/imagesToUpload/apokalipsa.jpeg").getFile().toPath();
String name = "apokalipsa.jpeg";
String originalFileName = "apokalipsa.jpeg";
String contentType = MediaType.IMAGE_JPEG_VALUE;
try {
content = Files.readAllBytes(path);
} catch (final IOException e) {
e.printStackTrace()
}
multiPartImage = new MockMultipartFile(name,
originalFileName, contentType, content);
}
@Sql("/testSql/personItem.sql")
def "should upload image"() {
expect:
mockMvc.perform(fileUpload("/items/2/images").file(multiPartImage))
.andExpect(status().isCreated())
}
}
я думаю, что все в порядке с составным файлом, потому что я проверил его...
а вот запрос и ответ:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /items/2/images
Parameters = {}
Headers = {Content-Type=[multipart/form-data;charset=UTF-8]}
Handler:
Type = controller.ItemController
Method = public org.springframework.http.ResponseEntity<?> controller.ItemController.uploadImage(java.lang.Long,org.springframework.web.multipart.MultipartFile,org.springframework.web.util.UriComponentsBuilder)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.multipart.support.MissingServletRequestPartException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 400
Error message = Required request part 'file' is not present
Headers = {X-Application-Context=[application:-1]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
Я был бы очень признателен за помощь, я пробовал много вариантов запроса, но безрезультатно.
@RequestParam#name
соответствуетMockMultipartFile#name
. - person Sotirios Delimanolis   schedule 05.10.2016