使用dropzone.js将excel文件上传到使用Java的后端服务器时出现问题。尝试上传文件时出现415错误。
这是我的代码,用于处理上传的excel文件,
@Path("/import/customers")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
@POST
public Response importCustomersExcel(InMultiPart inMP) throws IOException, JSONException {
System.out.println("PUT /import/customers");
CustomerService customerService = Container.getCustomerService();
FileProcessing processing = new FileProcessing();
Response response = null;
File retailersFile = null;
boolean validationError = false;
try {
retailersFile = processing.toFile(inMP);
customerService.validateImportExcel(retailersFile);
} catch (ValidationException e) {
validationError = true;
String errorMessage = e.getMessage();
if (e.getErrors() != null && !e.getErrors().isEmpty()) {
ExcelRowErrorMessageBuilder messageBuilder = new ExcelRowErrorMessageBuilder(e.getErrors());
errorMessage += messageBuilder.generateErrorMessage();
}
JSONObject json = new JSONObject();
json.put("error", errorMessage);
response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(json).build();
e.printStackTrace();
} catch (Exception e) {
validationError = true;
JSONObject json = new JSONObject();
json.put("error", e.getMessage());
response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(json).build();
e.printStackTrace();
} finally {
//delete the file if error
//else THE file is needed
if (validationError) {
boolean fileDeleted = FileProcessing.tryDelete(retailersFile);
System.err.println("File " + (retailersFile == null ? "" :retailersFile.getName() + " was deleted : " + fileDeleted));
}
}
if (!validationError) {
boolean isImportRunning = false;
synchronized (customerService) {
isImportRunning = customerService.isRetailersImportRunning();
if (!isImportRunning) {
customerService.setImportRunning(true);
}
}
if (!isImportRunning) {
CustomerImportRunner customerImportRunner = new CustomerImportRunner(customerService, retailersFile);
Thread thread = new Thread(customerImportRunner);
thread.start();
JSONObject json = new JSONObject();
json.put("info", "Import started successfully!");
response = Response.status(Status.OK).entity(json).build();
} else {
JSONObject json = new JSONObject();
json.put("error", "Import is already running");
response = Response.status(Status.INTERNAL_SERVER_ERROR).entity(json).build();
}
}
return response;
}
这是我的dropzone.js文件上传表单,
<form action="admin/rest/import/customers" class="dropzone" enctype="multipart/form-data"></form>
我已经在表格中故意添加了multipart / form-data,但是当我在上载时检查流程时,内容类型为Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryG1ZnT8kA25wpWLdW
。上载Excel文件时如何解决415错误,它显示415错误。我想念Java代码时会错过什么?请帮忙。谢谢。
答案 0 :(得分:2)
对于Jersey,您必须做两件事:
register(MultiPartFeature.class);
添加到您的ResourceConfig
importCustomersExcel(InMultiPart inMP)
更改为
importCustomersExcel(@FormDataParam("file") InputStream stream, @FormDataParam("file") FormDataContentDisposition fileDetail)
然后,您可以通过stream
访问文件内容,并通过fileDetail
访问文件详细信息。还要确保您的Dropzone-paramName为file
。