Below API works using postman:
Spring boot, backend code:
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@Slf4j
public class UploadFile {
@Autowired
private FTPClient con;
@PostMapping("/api/auth/uploadfiles")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
try {
boolean result = con.storeFile(file.getOriginalFilename(), file.getInputStream());
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
} catch (Exception e) {
log.error(e.getMessage(), e);
redirectAttributes.addFlashAttribute("message",
"Could not upload " + file.getOriginalFilename() + "!");
}
return "redirect:/";
}
}
ReactJS, frontend code: I have array of objects in the this.state.ipData
.
exportFTP = async () => {
const fromdata = this.state.ipData;
alert("Data Send to FTP server");
axios({
method: 'post',
url: 'http://localhost:8080/api/auth/uploadfiles',
data: fromdata,
header: {
'Accept': 'application/json ,text/plain, */*',
'Content-Type': 'multipart/form-data',
//'Authorization': 'Bearer '+JWTToken,
},
})
}
Button to trigger the function:
<button
style={{ marginRight: "2%", marginTop: "0.25%" }}
type="button"
className="btn btn-info"
onClick={() => this.exportFTP()}
>
Export to FTP
</button>
I need to change my frontend (ReactJS) code to as I did POST request using postman. The current JS code causes below error response:
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
Note that API works when using Postman. How to fix JS code?