When I send the file in the form of data, the API gets the data and can save the data but when it back the response it gets an exception.
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class java.io.ByteArrayInputStream and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: org.springframework.web.multipart.MultipartFile[][2]-org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile[0]-org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile["inputStream"])
Here is the TokenAuthenticationFilter
public class TokenAuthenticationFilter extends OncePerRequestFilter {
@Autowired
private TokenProvider tokenProvider;
@Autowired
private CustomUserDetailsService customUserDetailsService;
private static final Logger logger = LoggerFactory.getLogger(TokenAuthenticationFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
try {
String jwt = getJwtFromRequest(request);
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
Long userId = tokenProvider.getUserIdFromToken(jwt);
UserDetails userDetails = customUserDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
} catch (Exception ex) {
logger.error("Could not set user authentication in security context", ex);
}
filterChain.doFilter(request, response);
}
private String getJwtFromRequest(HttpServletRequest request) {
String bearerToken = request.getHeader("Authorization");
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
return bearerToken.substring(7, bearerToken.length());
}
return null;
}
}
Here is the react api call
export const savePost = async (postText, files) => {
const headers = new Headers();
headers.append("Authorization", 'Bearer ' + localStorage.getItem(ACCESS_TOKEN));
//headers.append('Content-Type', 'application/json');
const body = new FormData();
body.append('postText', postText);
/*let body = {
'postText': postText
}*/
for (let i = 0; i < files.length; i++) {
body.append('files', files[i]);
}
const requestOptions = {method: 'POST', headers: headers, body: body, redirect: 'follow'};
return await fetch(API_MAIN_ROOT + `/main-post`, requestOptions);
};
Here is the Backend Rest Api
@PostMapping(value = "/main-post-wth-sports-id", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@Timed
@Transactional
public ResponseEntity<String> createPostWithSportsId(@RequestParam String postText, @RequestParam Long sportsId, @RequestPart("files") MultipartFile[] files) throws URISyntaxException {
try {
log.debug("REST request to save createPostWithPostId : {} {}", postText, sportsId.toString());
Post post = new Post();
post.setPostText(postText.trim());
post.setTimestamp(LocalDateTime.now());
post.setStatus(true);
post.setLikeCount(0);
post.setCommentCount(0);
post.setShareCount(0);
post.setSportsType(sportsTypeRepository.findById(sportsId).orElseThrow(RuntimeException::new));
post.setUser(userRepository.findOneByEmailIgnoreCase(SecurityUtils.getCurrentUserLoginNonOptionalData()).orElseThrow(RuntimeException::new));
post = postService.createPost(post);
videoProcessingService.savePost(files, post);
return new ResponseEntity<>("Saved successfully!", HttpStatus.OK);
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Is there any way to solve the response issue?