0

У меня есть задача сформировать запрос такого вида:

POST /foo HTTP/1.1
Content-Length: 68137
Content-Type: multipart/form-data; boundary=---------------------------974767299852498929531610575

-----------------------------974767299852498929531610575
Content-Disposition: form-data; name="description"

some text
-----------------------------974767299852498929531610575
Content-Disposition: form-data; name="myFile"; filename="1.txt"
Content-Type: text/plain

(content of the uploaded file 1.txt)
-----------------------------974767299852498929531610575--

Чтобы он состоял из 2 частей: из текста и данных из файла.

Для формирования такого запроса я выполняю такой код на клиенте:

public void sendPOSTRequest(String url, String authData, String attachmentFilePath, String outputFilePathName) {
        
        String charset = "UTF-8";
        File binaryFile = new File(attachmentFilePath);
        String boundary = "------------------------" + Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
        String CRLF = "\r\n"; // Line separator required by multipart/form-data.
        int responseCode = 0;

        try {
            //Set POST general headers along with the boundary string (the seperator string of each part)
            URLConnection connection = new URL(url).openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            //connection.addRequestProperty("User-Agent", "CheckpaySrv/1.0.0");
            //connection.addRequestProperty("Accept", "*/*");
            //connection.addRequestProperty("Authentication", authData);

            OutputStream output = connection.getOutputStream();
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);

            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data;").append(CRLF);
            writer.append("Content-Type: application/json").append(CRLF);// + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
            writer.append("{\"a\":\"asda\"}").append(CRLF);// + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
            writer.append(CRLF);
            
            // Send binary file - part
            // Part header
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
            writer.append("Content-Type: application/octet-stream").append(CRLF);// + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
            writer.append(CRLF);
            writer.flush();

            // File data
            Files.copy(binaryFile.toPath(), output);
            output.flush();

            // End of multipart/form-data.
            writer.append(CRLF).append("--" + boundary + "--").flush();

            //Отправить запрос и ожидать ответ от сервера
            responseCode = ((HttpURLConnection) connection).getResponseCode(); 
 
            if (responseCode != 200) //We operate only on HTTP code 200
            {
                return;
            }

            InputStream Instream = ((HttpURLConnection) connection).getInputStream();

            // Write PDF file 
            BufferedInputStream BISin = new BufferedInputStream(Instream);
            FileOutputStream FOSfile = new FileOutputStream(outputFilePathName);
            BufferedOutputStream out = new BufferedOutputStream(FOSfile);

            int i;
            while ((i = BISin.read()) != -1) {
                out.write(i);
            }

            // Cleanup
            out.flush();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

Этот запрос я пробую обработать таким кодом на сервере:

@RequestMapping(value = "/test6", method = RequestMethod.POST, consumes = { MediaType.MULTIPART_FORM_DATA_VALUE })
    public String test6(@RequestPart String part1) {
        System.out.println("data1: "+part1);
        System.out.println("Stop");
        return "string1";
    }

В процессе отправки post запроса по адресу: http://localhost:8080/test6, на сервере я получаю такое сообщение:

WARN 2356 --- [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : 
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: 
Required request part 'part1' is not present]

Подскажите как можно обработать такой запрос post с типом multipart/form-data?

1 ответ 1

0

Для достижения поставленной цели: отправка запроса, в котором текст+файл нужно внести такие изменения:

в коде клиента, который выполняет запрос:

     writer.append("--" + boundary).append(CRLF);
     writer.append("Content-Disposition: form-data; name=\"text\"").append(CRLF);
     writer.append("Content-Type: application/json").append(CRLF);
     writer.append(CRLF);
     writer.append("{\"a\":\"asda\"}").append(CRLF);
     writer.append(CRLF);
        
     // Send binary file - part
     // Part header
     writer.append("--" + boundary).append(CRLF);
     writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF);
     writer.append("Content-Type: application/octet-stream").append(CRLF);// + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF);
     writer.append(CRLF);
     writer.flush();

в коде сервера, который обрабатывает запрос:

@RequestMapping(value = "/test7", method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
public String test7(@RequestParam ("text") String text, @RequestParam("file") MultipartFile file, ModelMap modelMap) {
    System.out.println("json: "+text);
    System.out.println("fileSize: "+file.getSize()+" bytes");
    
    System.out.println("return response...");
    return "response to client";
}

Идея в связывании части из запроса name="text" где text связан с частью из контроллера, который обрабатывает этот запрос @RequestParam ("text") String text, это мы проделываем и со второй частью запроса: name="file" где file связан с @RequestParam("file") MultipartFile file, ModelMap modelMap .

При таком подходе можно избавиться от ошибки связи элементов: Required request part 'text' is not present или Required request part 'file' is not present

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.