我无法弄清楚如何使用带有spock的mockMvc上传jpg文件。当我用邮递员手动执行请求时,一切正常,图像上传。我正在使用春季靴子
这是控制器:
@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())
}
}
我认为multipart文件的一切都很好,因为我已经测试了它......
以下是请求和回复:
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 = []
我真的很感谢帮助,我尝试了许多变化但没有用的