0

Hi I am trying to connect a react-app with an api that i did with react. The problem is that I can not send a multipartFile to the api side. If I do the request with postman, work correctly. But if i do the request in my react-app do not work.

@Spring Spring code

 @PostMapping("/save")
public ResponseEntity<?> save(@RequestParam(required = false) String folderId, @RequestParam MultipartFile multipartFile) throws IOException{
    //folder exist??
    int id = Integer.parseInt(folderId);
    Optional<Folder> folderOpt = folderService.get(id);
    if(folderOpt.isEmpty()){
        return new ResponseEntity<>("The folder does not exist", HttpStatus.NOT_FOUND);
    }
    Folder folder = folderOpt.get();

    //connect with cloudinary
    BufferedImage bi = ImageIO.read(multipartFile.getInputStream());
    if (bi == null){ //is it an image??
        return new ResponseEntity("Image does not valid", HttpStatus.BAD_REQUEST);
    }
    Map result = cloudinaryService.upload(multipartFile);

    //save in the bd
    Image img = new Image(
    (String)result.get("original_filename"),
                (String)result.get("url"),
                (String)result.get("public_id"));

    img.setFolder(folder);
    imageService.save(img);
    return new ResponseEntity<>(HttpStatus.OK);

}

@Postman Postman request

@React React code

    const [imageSelected,setImageSelected] = useState("")
  const uploadImage = (files) =>{
    const formData = new FormData();
    formData.append("file", files[0]);

    console.log(formData)   
    ImagenServices.postImage(formData,id)
}


return(
    <div className={Styles.container}>
        <div>
            <input type="file" id="myFileField" onChange={(event) => {setImageSelected(event.target.files)}}/>
            <button onClick={() => uploadImage(imageSelected)}>Upload image</button>
        </div>
    </div>
)

@PostImage service Service code

async postImage(file,idFolder){
    let request = await fetch(REST_API_URL + "/save",{
        method: "POST",
        body:{
            'folderId': idFolder,
            'multipartFile': file
        },
        headers:{
            'Accept': 'application/json, text/plain, */*',
            'Content-Type': false
        }}, 
        )
    }
}

@Error console error

ERROR 95787 --- [io-8080-exec-10] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Current request is not a multipart request] with root cause

org.springframework.web.multipart.MultipartException: Current request is not a multipart request at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.handleMissingValueInternal(RequestParamMethodArgumentResolver.java:210) ~[spring-web-5.3.22.jar:5.3.22]

ddi02
  • 1
  • 1

0 Answers0