I have a working controller for uploading csv's in a post request. Status 200 in postman, status 400 while testing. I'm struggling to see what the problem is.
Controller:
@RestController
@RequestMapping("/csv")
public class CsvController {
final CsvService csvService;
public CsvController(CsvService csvService) {
this.csvService = csvService;
}
@PostMapping("/upload")
public ResponseEntity<Response> uploadFile(@RequestParam("file")MultipartFile file) {
if(CsvHelper.hasCSVFormat(file)) {
Response response = csvService.save(file);
return new ResponseEntity<>(response, HttpStatus.valueOf(response.getStatus()));
}
Response response = new Response().setStatus(400).setMessage("Please upload a CSV file");
return new ResponseEntity<>(response, HttpStatus.valueOf(response.getStatus()));
}
}
CsvHelper Util:
public class CsvHelper {
public static String TYPE = "text/csv";
public static boolean hasCSVFormat(MultipartFile file) {
return TYPE.equals(file.getContentType());
}
}
Test:
@ExtendWith(SpringExtension.class)
@WebMvcTest(value = CsvController.class)
public class TestControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private CsvService csvService;
@Test
void status200WhenUploadingCSV() throws Exception {
MockMultipartFile mockMultipartFile = new MockMultipartFile(
"multipartFile",
"template.csv",
"text/csv",
new ClassPathResource("template.csv").getInputStream());
mockMvc.perform(MockMvcRequestBuilders.multipart("/csv/upload")
.file(mockMultipartFile))
.andExpect(status().isOk());
}}
When the test fails I can see this Resolved Exception: Type = org.springframework.web.multipart.support.MissingServletRequestPartException
CodePudding user response:
this error is because of the file size you are uploading. It can be fixed by setting max upload size.
add this to your main class.
@Bean(name = "multipartResolver")
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(10000000L);
return new CommonsMultipartResolver();
}
CodePudding user response:
This exception occurs sometimes when the @RequestParam("file")MultipartFile file
the file
is being empty or it is not receiving any attribute.
You can see here.
Maybe it can solve your problem.
Or you can specify your file size in the application.properties
file as:
spring.http.multipart.max-file-size=10MB
spring.http.multipart.max-request-size=11MB