415 Ошибка неподдерживаемого типа носителя в сервлете Java; Загрузка файла в Excel - PullRequest
0 голосов
/ 28 августа 2018

Я столкнулся с ошибкой 415 при загрузке файла Excel через браузер с помощью Dropzone.js. Когда я проверял инструменты разработчика в Chrome, тип загружаемого файла Excel был multipart / form-data; граница = ---- WebKitFormBoundaryH0KdsQU0Yhr3U2dA

На стороне сервера у меня есть способ принять загруженный файл Excel, но, похоже, он не соответствует нужному типу содержимого, который ожидает мой метод. Вот мой код сервера:

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.wink.common.model.multipart.InMultiPart;
import org.apache.wink.json4j.JSONArray;
import org.apache.wink.json4j.JSONException;
import org.apache.wink.json4j.JSONObject;

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

Подскажите, пожалуйста, где я ошибаюсь в своем коде? Если вам нужен код для других классов, я могу предоставить. Ошибка 415 Неподдерживаемый тип носителя. Пожалуйста помоги. Я новичок в Java.

...