Не удается выполнить запрос POST AWS Lambda и API-шлюз - PullRequest
1 голос
/ 14 февраля 2020

У меня есть вышеуказанная конфигурация для шлюза API, который использует лямбду. Я пытаюсь отправить pdf, манипулировать им, а затем вернуть новое содержимое в браузер по маршруту / upload.

    @RequestMapping("/upload")
    public ResponseEntity upload( @RequestParam("files") MultipartFile file) throws IOException {
        String path = "C:\\Users\\nehamaj\\Downloads\\JAVA\\SpringBootFileUpload\\yikes.pdf";
        String path2 =  System.getProperty("java.io.tmpdir");
        file.transferTo(new File(path2+"\\yeahboy2.pdf" )); //transfer the uploaded file to this path AND convert its type to File
        ResponseEntity respEntity = null; //init response entity

        PdfDocument pdfDoc = new PdfDocument(new PdfReader(path2+"\\yeahboy2.pdf"), new PdfWriter(path2+"\\yeahboy.pdf"));
        // open the pdf doc by reading in the newly typed File that was created from the uploaded file
        // write the file to the specified path
        for (int p = 1; p <= pdfDoc.getNumberOfPages(); p++) {
            if (p == 1) {
                PdfPage page = pdfDoc.getPage(p); //get the first page
                Rectangle media = page.getCropBox();
                if (media == null) {
                    media = page.getMediaBox();
                }
                float llx = media.getX() + 0;
                float lly = media.getY() + 250; //do the croping dimensions
                float w = media.getWidth() - 250;
                float h = media.getHeight() - 500;
                // It's important to write explicit Locale settings, because decimal separator differs in
                // different regions and in PDF only dot is respected
                String command = String.format(Locale.ENGLISH,
                        // re operator constructs a rectangle
                        // W operator - sets the clipping path
                        // n operator - starts a new path
                        // q, Q - operators save and restore the graphics state stack
                        "\nq %.2f %.2f %.2f %.2f re W n\nq\n", llx, lly, w, h); //establish the clipping
                // The content, placed on a content stream before, will be rendered before the other cont
                // and, therefore, could be understood as a background (bottom "layer")
                PdfPage pdfPage = pdfDoc.getPage(p);
                new PdfCanvas(pdfPage.newContentStreamBefore(), pdfPage.getResources(), pdfDoc)
                        .writeLiteral(command); //do the clipping on the specified page
                // The content, placed on a content stream after, will be rendered after the other content
                // and, therefore, could be understood as a foreground (top "layer")
//            new PdfCanvas(pdfPage.newContentStreamAfter(), pdfPage.getResources(), pdfDoc)
//                    .writeLiteral("\nQ\nQ\n");
            }

        }
        pdfDoc.close(); //CLOSE THE DOC OR THIS SHITE WILL NOT WORK

        InputStream inputStream = new FileInputStream(path2+"\\yeahboy.pdf"); //read the literal bytes
        // from the file at this location, we wrote to here via the pdf writer
        byte[] out = org.apache.commons.io.IOUtils.toByteArray(inputStream); //make a byte array from the bytes of the input stream
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type","application/pdf");
        respEntity = new ResponseEntity(out,responseHeaders, HttpStatus.OK);
        return respEntity;

    }

Я получаю следующую ошибку в трассировке стека. Может кто-нибудь, пожалуйста, дайте мне предложения о том, как вернуть PDF в браузер (для просмотра) ??

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.lang.NoSuchMethodError: org.apache.commons.io.IOUtils.readFully(Ljava/io/InputStream;[B)V

1 Ответ

1 голос
/ 28 февраля 2020

Я все еще вижу много людей, которые приходят с такой же ошибкой MultipartException. Документация apache сбивает с толку, и для многих решение может заключаться в использовании правильной зависимости.

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...