【发布时间】:2020-08-27 18:39:30
【问题描述】:
我正在构建一个小的 springboot 应用程序,它在 Neo4j 图形数据库上进行 CRUD 操作。其中一项操作是使用 CSV 文件批量插入。
我收到以下错误: 来自铬
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";
}
}
这是使用 thymleaf 模板的网页:
<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();
});
感谢任何帮助。谢谢。
【问题讨论】:
标签: spring-boot tomcat file-upload neo4j