简体   繁体   English

AJAX:将文件发送到Servlet并在新窗口中打开响应

[英]AJAX: Send file to Servlet and open response in new window

in my application, users can edit an ODF file via WebODF ( http://webodf.org/ ). 在我的应用程序中,用户可以通过WebODF( http://webodf.org/ )编辑ODF文件。 On save, i want to send the edited file to a servlet, have it convert to PDF via ODFDOM ( http://code.google.com/p/xdocreport/wiki/ODFDOMConverterPDFViaIText ) and open in a new window. 保存时,我想将编辑后的文件发送到servlet,让它通过ODFDOM( http://code.google.com/p/xdocreport/wiki/ODFDOMConverterPDFViaIText )转换为PDF,然后在新窗口中打开。

Currently i am trying to do this via AJAX. 目前,我正在尝试通过AJAX进行此操作。 Everything works fine up to the point where i try to open the received PDF file. 一切正常,直到我尝试打开接收到的PDF文件为止。

My Javascript: 我的Javascript:

function showPDF(pServletUrl)
        {               
            var successCallback = function(pData)
            {
                var mimetype = "application/vnd.oasis.opendocument.text";
                var blob = new Blob([pData.buffer], {type: mimetype});
                var formData = new FormData();
                formData.append("file", blob, "test.odt");
                jQuery.ajax({
                    type: "POST", 
                    url: pServletUrl,
                    async: false, 
                    data: formData,
                    processData: false,
                    contentType: false, 
                    success: function(pSuccessData) 
                    { 
                        window.open(pSuccessData);
                    }, 
                    error: function(pErrorData) 
                    { 
                        console.log(pErrorData); 
                    }
                });
            }

            var errorCallback = function(data)
            {
                console.log(error);
            }

            _canvas.odfContainer().createByteArray(successCallback, errorCallback);
        }

My servlet: 我的servlet:

public void handleRequest(HttpServletRequest pRequest, HttpServletResponse pResponse) throws ServletException, IOException
{
    BufferedInputStream tBufferedInput = null;
    BufferedOutputStream tBufferedOutput = null;

    try 
    {
        List<FileItem> tItems = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(pRequest);
        for (FileItem tItem : tItems) 
        {
            if (!tItem.isFormField()) 
            {
                String tFieldname = tItem.getFieldName();
                String tFilename = FilenameUtils.getName(tItem.getName());
                InputStream tFilecontent = tItem.getInputStream();

                if("file".equals(tFieldname))
                {
                    tBufferedInput = new BufferedInputStream(tFilecontent);
                    pResponse.reset();
                    pResponse.setHeader("Content-Type", "application/pdf");
                    pResponse.setHeader("Content-Disposition", "inline; filename=\"" + "test.pdf" + "\"");
                    tBufferedOutput = new BufferedOutputStream(pResponse.getOutputStream(), 10240);

                    this.getOdtAsPdf(tBufferedInput, tBufferedOutput);

                    tBufferedOutput.flush();
                }
            }
        }
    }   
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            tBufferedInput.close();
            tBufferedOutput.close();
        }
        catch(Exception e)
        {

        }
    }
}

private void getOdtAsPdf(InputStream pInputStream, OutputStream pOutputStream) throws Exception
{
    OdfDocument tOdfDocument = OdfDocument.loadDocument(pInputStream);
    PdfOptions tPdfOptions = PdfOptions.create();
    PdfConverter.getInstance().convert(tOdfDocument, pOutputStream, tPdfOptions);
}

It seems like Javascript wants to parse the recieved PDF file as a URL and (obviously) fails doing so. 似乎Javascript希望将收到的PDF文件解析为URL,并且(显然)无法这样做。 Is there a way to just open the file in a new window or do i have to find another way to do this? 有没有一种方法可以在新窗口中打开文件,还是我必须找到另一种方法来执行此操作?

You can't open the file using Ajax. 您无法使用Ajax打开文件。 This is a security restriction fo javascript. 这是javascript的安全限制。 You have a few workarounds: 您有一些解决方法:

  1. use a plugin which gives a Ajax type experience but opens a file in a new window. 使用可提供Ajax类型体验但在新窗口中打开文件的插件。 more details here 这里有更多细节
  2. have a form which is submitted to a new window. 具有提交到新窗口的表单。 <form target=_blank /> this will cause a new window to open thus not changing the contents of your current page. <form target=_blank />这将导致一个新窗口打开,因此不会更改当前页面的内容。
  3. Another option (not so neat) is to store the file in session and in the response of your AJAX, pass the id. 另一个选择(不是很简洁)是将文件存储在会话中,并在AJAX的响应中传递ID。 Then using Javascript make a call using window.open('downloadurl?id') which will send the response of your PDF file. 然后使用Javascript使用window.open('downloadurl?id')进行调用,它将发送您的PDF文件的响应。

You can make use an embed tag to display your blob after you make an ajax call. 进行ajax调用后,可以使用embed标签显示blob。

Use createObjectUrl method to get url from blob and then display your pdf. 使用createObjectUrl方法从blob获取URL,然后显示pdf。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM