org.apache.tomcat.util.http.fileupload.FileUploadException:由于未找到多部分边界,因此请求被拒绝

时间:2020-05-12 02:55:11

标签: spring-boot tomcat file-upload neo4j

我正在构建一个小的springboot应用程序,该程序在Neo4j图形数据库上进行CRUD操作。一项操作是使用CSV文件批量插入。

我遇到这些错误: 从chrome

Access to XMLHttpRequest at 'http://localhost:9090/neo4jtest/api/employees/upload-csv' from origin 'http://localhost:8090' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

这是控制器(我删除了无用的映射):

@RestController
@RequestMapping(path = "/employees")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/upload-csv")
    public String uploadCSVFile(@RequestParam("file") MultipartFile file, Model model) {

        // validate file
        if (file.isEmpty()) {
            model.addAttribute("message", "Please select a CSV file to upload.");
            model.addAttribute("status", false);
        } else {
            // parse CSV file to create a list of `employee` objects
            try (Reader reader = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
                // create csv bean reader
                CsvToBean<Employee> csvToBean = new CsvToBeanBuilder<Employee>(reader).withType(Employee.class).withIgnoreLeadingWhiteSpace(true).build();
                // convert `CsvToBean` object to list of employees
                // TODO : save employees into neo4j
                // save employees list on model
                model.addAttribute("employees", Employees.builder().employeeList(csvToBean.parse()).build());
            } catch (Exception ex) {
                model.addAttribute("message", "An error occurred while processing the CSV file.");
                model.addAttribute("status", false);
            }
        }   
        return "list";
    }
}

这是使用百里香模板的网页:

<script>
$(document).ready(function() {
    $("#btn-upload-csv").click(function() {
        $('#neo4j-filechooser').trigger('click');
    });

    $('#neo4j-filechooser').on('change', function() {
        myfiles = this.files; //save selected files to the array
        console.log(myfiles[0]); //show them on console
        formdata = new FormData();
        formdata.append("file",myfiles[0])
        $.ajax({
            url: "http://localhost:9090/neo4jtest/api/employees/upload-csv",
            type: "POST",
            processData: false,
            contentType: false,
            headers: {
                "Content-Type": "multipart/form-data",
                "Access-Control-Allow-Origin":"*",
                "Access-Control-Allow-Methods": "POST",
                "Access-Control-Allow-Headers": "Content-Type, Authorization"
            },
            data: formdata
        }).then(function(data) {
           $('.greeting-id').append(data.id);
           $('.greeting-content').append(data.content);
        });
    }).click();
});

感谢您的帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

从错误堆栈跟踪中可以看到错误实际上是:

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

即,即使设置了content-type,也未设置多部分边界。因此,问题是您要自行设置Content-Type ,将其保留为空白,以便jquery可以为您完成。问题实际上是在您的请求中,按照规范:

多部分实体的Content-Type字段需要一个参数, “边界”,用于指定封装边界。的 封装边界定义为完全由两个组成的线 连字符(“-”,十进制代码45),后跟边界 Content-Type标头字段中输入参数值。

在您的jquery请求中,您正在设置processData: false, 和contentType: false,这会强制jquery设置内容类型和边界。但是,在请求的标头部分中,您再次手动添加了content-type。从代码中将其删除,然后尝试。如果不起作用,请您分享示例数据,以便我们进行更多分析。如果您使用旧版本的jquery或从旧版本的浏览器运行它,也会发生此问题。

尝试以下代码:

<script>
$(document).ready(function() {
    $("#btn-upload-csv").click(function() {
        $('#neo4j-filechooser').trigger('click');
    });

    $('#neo4j-filechooser').on('change', function() {
        myfiles = this.files; //save selected files to the array
        console.log(myfiles[0]); //show them on console
        formdata = new FormData();
        formdata.append("file",myfiles[0])
        $.ajax({
            url: "http://localhost:9090/neo4jtest/api/employees/upload-csv",
            type: "POST",
            processData: false,
            contentType: false,
            headers: {
                "Access-Control-Allow-Origin":"*",
                "Access-Control-Allow-Methods": "POST",
                "Access-Control-Allow-Headers": "Content-Type, Authorization"
            },
            data: formdata
        }).then(function(data) {
           $('.greeting-id').append(data.id);
           $('.greeting-content').append(data.content);
        });
    }).click();
});
相关问题