Skip to content

Exporting formData from React to Spring boot backend

React code for build jsonBlob object

function  jsonBlob(obj) {
  return new Blob([JSON.stringify(obj)], {
    type: "application/json",
  });
}

 exportFTP = () => {
    const formData = new FormData();
    formData.append("file", jsonBlob(this.state.ipData));
    alert("Logs export to FTP server")

    axios({
      method: "post",
      url: "http://localhost:8080/api/auth/uploadfiles",
      data: formData,
      headers: {
        Accept: "application/json ,text/plain, */*",
        "Content-Type": "multipart/form-data",
      },
    });
  };

Spring boot backend that accepts for frontend request

public class UploadFile {
    @Autowired
    private FTPClient con;

    @PostMapping("/api/auth/uploadfiles")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {

        try {
            boolean result = con.storeFile(file.getOriginalFilename(), file.getInputStream());
            System.out.println(result);

        } catch (Exception e) {
            System.out.println("File store failed");
        }

        return "redirect:/";
    }

I want to figure out when I called the function from the frontend it’s working properly but I change the state its doesn’t send the object to the backend while the file appears in the directory. if I delete the file then only send it again and save it on the directory. How I save multiple files while doesn’t delete the previous ones

Thank you very much for your time and effort.

Answer

In React application I used props to pass the file name from a different state and make sure to remove,

"Content-Type": "multipart/form-data",

Main function in React,

 exportFTP = ({props from different state}) => {
    const formData = new FormData();
    formData.append("file", jsonBlob(this.state.ipData),{You can use this parm for pass name});
    alert("Logs export to FTP server")

    axios({
      method: "post",
      url: "http://localhost:8080/api/auth/uploadfiles",
      data: formData,
      headers: {
        Accept: "application/json ,text/plain, */*"
 
      },
    });
  };

And back end code I used same to get the original name then Its appears with the right name.

con.storeFile(file.getOriginalFilename(), file.getInputStream());

Chears !!