【问题标题】:Java - downloading ByteArrayOutputStream to client side?Java - 将 ByteArrayOutputStream 下载到客户端?
【发布时间】:2018-02-20 05:21:29
【问题描述】:

我是 Java 新手,来自前端开发人员。要求是将多个 pdf 文件编辑并压缩到流中的一个 zip 文件夹中,然后将其扔回客户端/前端。目前,我正在使用 ByteArrayOutputStream 来捕获流并创建一个文件并将字节写入其中。我被困在我不确定如何通过标头将 zip 发送回客户端的地方。我将我的服务代码和前端代码放在这里。

@POST
@Path("/generator")
@Consumes(MediaType.APPLICATION_JSON)
@Produces("application/pdf")
            public Response getOrg(PreApprovedAds ads) {

                Response response = null;
                logger.log(Level.FINE, "In Get PDF Method");
                boolean success = true;

                try {

                    System.out.println("gettign name  = "+ads.getName());
                    totalRequestReceived++;


                    System.out.println("Front-End Data Below v--v "+"\n");
                    System.out.println("Name = "+ads.getName()+"\n"+ "Company = " + ads.getCompany()+ "\n"+ "Country = "+ads.getCountry() +"\n"+"List = "+ ads.getLinks());

                    zipfolder zip_modify = new zipfolder();

                    String fieldData1 = ads.getName();
                    String fieldData2 = ads.getCompany();
                    String fieldData3 = ads.getCountry();


                    List <String> pdfLinks= ads.getLinks();


                //  String string = zip_modify.editandzip(fieldData1,fieldData2,fieldData3, pdfLinks);
                    zip_modify.editandzip(fieldData1,fieldData2,fieldData3, pdfLinks);



                    logger.log(Level.FINE, "Out Get PDF Method");
                    //response = Response.status(Response.Status.OK).entity(string).build();




                } catch (Exception e) {
                    logger.log(Level.INFO, "Error: " + e.getMessage());
                    logger.log(Level.FINE, "Error: " + CoreUtil.getStackTrace(e));
                    success = false;
                    response = Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                            .entity(PropertyUtil.getProperty("ERROR_MESSAGE")).build();
                } finally {
                    if (success) {
                        totalSucceedResponse++;
                    } else {
                        totalFailedResponse++;
                    }
                }

                return response;

            }

public class zipfolder {

public String editandzip (String data1,String data2,String data3, List<String> links) {

    try {

        PdfEditor writetopdf = new PdfEditor();


        File f = new File("C:/Users/JayAcer/workspace/test/test.zip");


        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));

        int a = 0;
        for (String i : links){
            System.out.println("opening connection");
            URL url = new URL(i);
            InputStream in = url.openStream();

            ByteArrayOutputStream bao = writetopdf.manipulatePdf(in, data1 , data2, data3);

            byte[] ba = bao.toByteArray();
            ZipEntry entry = new ZipEntry("newform" + a +".pdf");
            entry.setSize(ba.length);
            zos.putNextEntry(entry);
            zos.write(ba);
            a++;
            in.close();
        }


        zos.close();

        System.out.println("File downloaded");

    } catch (Exception e) {
        System.out.println("Error");
        e.printStackTrace();
    }
    return data2;


}

}

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("button").click(function () {
                var url = "http://localhost:9080/test/api/pdf/generator";
                var data =
                    {
                        "name": "Jay Chacko ",
                        "company": "Element blue",
                        "country": "USA",

                        "links": [
                            "http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/form.pdf", "http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/form.pdf", "http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/form.pdf"

                        ]
                    }
                $.ajax({
                    type: "POST",
                    url: url,
                    data: JSON.stringify(data),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) { alert(data); },
                    failure: function (errMsg) {
                        alert(errMsg);
                    }
                });
            });
        });
    </script>
</head>

<body>

    <h1>Test sending From Front-End</h1>
    <button style=" background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;">click me</button>
</body>

</html>

【问题讨论】:

    标签: javascript java rest jax-rs


    【解决方案1】:

    我几乎不得不返回我的 byarrayoutstream 并将其作为响应发送。在服务中。

    ZipOutputStream zos = new ZipOutputStream(byteArrayOutputStream);
    
            int a = 0;
            for (String i : links){
                System.out.println("opening connection");
                URL url = new URL(i);
                InputStream in = url.openStream();
    
                ByteArrayOutputStream bao = writetopdf.manipulatePdf(in, data1 , data2, data3);
    
                byte[] ba = bao.toByteArray();
                ZipEntry entry = new ZipEntry("newform" + a +".pdf");
                entry.setSize(ba.length);
                zos.putNextEntry(entry);
                zos.write(ba);
                a++;
                in.close();
            }
    
    
            zos.close();
    
            System.out.println("File downloaded");
            return byteArrayOutputStream;
    

    response = Response.status(Response.Status.OK).type("application/zip").entity(new StreamingOutput() {
                @Override
                public void write(OutputStream output) throws IOException, WebApplicationException {
                       output.write(byteArrayOutputStream.toByteArray());
                       output.flush();
                   }
                });
            response.header("content-disposition", "attachment; filename=\"testZip.zip\"");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 2015-04-01
      • 1970-01-01
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多