在 Java 中上传 excel 文件时,如何修复错误 415 不支持的媒体类型错误?

How to fix Error 415 Unsupported media type error when uploading an excel file in Java?

我在使用 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 代码上添加什么?请帮忙。谢谢。

对于泽西岛你必须做两件事:

  1. register(MultiPartFeature.class); 添加到您的 ResourceConfig
  2. 将您的方法 importCustomersExcel(InMultiPart inMP) 更改为 importCustomersExcel(@FormDataParam("file") InputStream stream, @FormDataParam("file") FormDataContentDisposition fileDetail)

然后您可以通过 stream 访问文件内容,通过 fileDetail 访问文件详细信息。还要确保您的 Dropzone-paramName 是 file.