Весенняя загрузка, читающая загруженный пользователем файл CSV - PullRequest
1 голос
/ 28 октября 2019

в моей системе мне нужно загрузить файл CSV и сохранить детали в базе данных. В качестве первого шага я сохраняю загруженный файл в выбранной папке. Однако, когда я пытаюсь это сделать, я получаю следующее сообщение об ошибке (ошибка показана на рисунке). Может кто-нибудь помочь мне решить это? Спасибо.

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 файл

<!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>

Ответы [ 2 ]

1 голос
/ 29 октября 2019

Вы не должны отключать коры без надлежащей причины и оценки рисков, связанных с этим. Отметьте этот пост .

Специально, учитывая, что тимилиф очень легко добавит токен csrf в ваши формы;просто измените атрибут action вашей формы на th:action. Это создаст скрытый ввод с токеном, который будет отправлен вместе с вашей формой, и успешно выполнит ваш запрос POST.

Это действие аналогично добавлению ввода самостоятельно (хотя в вашем случае нет причин делать это)):

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

РЕДАКТИРОВАТЬ: Просто для записи, если кто-то читает это позже и нуждается в выполнении запроса через ajax, вы можете добавить токен следующим образом (используя jquery для вызова):

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

$.ajax({
    beforeSend: function(xhr) {
      xhr.setRequestHeader(header, token);
    },
    ....
})
0 голосов
/ 29 октября 2019

Решил это, добавив следующий код в WebSecurityConfig

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