2

in my system i need to upload a CSV file and save details in the database. As the first step i'm saving the uploaded file in a selected folder.However when i try this i get the following error message.(Error shown in the image). Can someone help me to solve this? Thank you.

enter image description here

subjectController

@Controller
public class SubjectController {
    @Autowired
    private SubjectDAO subjectDAO;

    @Autowired
    private CourseDAO courseDAO;

    @Autowired
    private LectureHallDAO lectureHallDAO;

    private final SubjectRepository subjectRepository;



    public SubjectController(SubjectRepository subjectRepository) {
        this.subjectRepository = subjectRepository;
    }


    //Save the uploaded file to this folder
    private static String UPLOADED_FOLDER = "F://temp//";

    @GetMapping("/sub")
    public String index() {
        return "addAllSubject";
    }

    @PostMapping("/upload") // //new annotation since 4.3
    public String singleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes) {

        if (file.isEmpty()) {
            //redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
            return "redirect:uploadStatus";
        }

        try {
            // Get the file and save it somewhere
            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
            Files.write(path, bytes);

            //redirectAttributes.addFlashAttribute("message",
            //        "You successfully uploaded '" + file.getOriginalFilename() + "'");

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "redirect:/uploadStatus";
    }

    @GetMapping("/uploadStatus")
    public String uploadStatus() {
        System.out.println("error");
        return "uploadStatus";
    }

}

addAllSubjects html file

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>

<h1>Spring Boot file upload example</h1>

<form method="POST" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file" /><br/><br/>
    <input type="submit" value="Submit" />
</form>

</body>
</html>
Ayesh17
  • 153
  • 1
  • 1
  • 16

2 Answers2

1

You shouldn't disable cors without a proper reason and an evaluation of the risks of doing so. Check this post.

Specially, given that thymeleaf will add the csrf token in your forms in a very easy way; just change your form's action attribute for th:action. This will create a hidden input with the token that will be submitted with your form, succesfully making your POST request.

Doing this has the same effect of adding the input yourself (no reason to do this in your case though):

<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />`

EDIT: Just for the record in case someone reads this later and is in need of making the request via ajax, you can add the token in the following way (using jquery for the call):

var token = '[[${_csrf.token}]]';
var header = '[[${_csrf.headerName}]]';

$.ajax({
    beforeSend: function(xhr) {
      xhr.setRequestHeader(header, token);
    },
    ....
})
Jorge.V
  • 1,329
  • 1
  • 13
  • 19
0

Solved this by adding the following code to the WebSecurityConfig

@Override
    protected void configure(HttpSecurity http) throws Exception {         
        //to upload
        http.cors().and().csrf().disable();
    }
Ayesh17
  • 153
  • 1
  • 1
  • 16