【问题标题】:Spring boot reading a user uploaded csv fileSpring Boot 读取用户上传的 csv 文件
【发布时间】:2020-02-23 10:15:36
【问题描述】:

在我的系统中,我需要上传一个 CSV 文件并将详细信息保存在数据库中。作为第一步,我将上传的文件保存在选定的文件夹中。但是,当我尝试此操作时,我收到以下错误消息。(错误显示在图像中)。有人可以帮我解决这个问题吗?谢谢。

主题控制器

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

【问题讨论】:

    标签: hibernate spring-boot thymeleaf


    【解决方案1】:

    您不应在没有正当理由和评估这样做的风险的情况下禁用 cors。检查this post

    特别是,鉴于 thymeleaf 会以一种非常简单的方式在您的表单中添加 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);
        },
        ....
    })
    

    【讨论】:

    • 非常感谢。它工作得很好,而且还了解 cors 的重要性
    • @Ayesh17 没问题,godspeed!
    【解决方案2】:

    通过将以下代码添加到 WebSecurityConfig 来解决此问题

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

    【讨论】:

      猜你喜欢
      • 2019-05-05
      • 2021-03-01
      • 2022-11-11
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 1970-01-01
      相关资源
      最近更新 更多