how to write a file object on server response and without saving file on server?

十年热恋 提交于 2019-12-01 11:08:02
public ModelAndView writeFileContentInResponse(HttpServletRequest request, HttpServletResponse response) throws IOException {

        FileInputStream inputStream = new FileInputStream("FileInputStreamDemo.java");  //read the file

        response.setHeader("Content-Disposition","attachment; filename=test.txt");
        try {
            int c;
            while ((c = inputStream.read()) != -1) {
            response.getWriter().write(c);
            }
        } finally {
            if (inputStream != null) 
                inputStream.close();
                response.getWriter().close();
        }

        }

It has been years since I've used Spring, and I'm unfamiliar with DWR, but the essence of your question is basic to the web.

The answer is yes, you can. In effect, you need to set the HTTP header Content-Disposition: attachment, then stream down the contents. All of this will be in the response to the original request (as opposed to sending back a link).

The actual code to achieve this will depend on your circumstances, but this should get you started.

you call the method from Java Script, right? I didn't really understand how Spring is related in this flow, but as far as I know DWR allows you to produce Java Script Stubs and call the Java methods of the exposed bean directly on server right from your java script client code.

You can read the file byte-by-byte and return it from your java method as long as it really returns a byte array. However what would you do with this byte array on client?

I just think in this specific flow you shouldn't use the DWR but rather issue an ordinar AJAX request (if DWR can wrap it somehow for convenience - great). This request shouldn't come to DWRServlet, but rather be proceeded by a regular servlet/some web-based framework, like Spring MVC :) Once the request comes to the servlet, use

response.setHeader("Content-Disposition","attachment; filename=test.txt");

as was already stated.

Hope this helps, Good luck! Mark

An example which return a excel to download from client:

//Java side:

public FileTransfer getExcel(Parametros param){
   byte[] result = <here get data>;
   InputStream myInputStream = new ByteArrayInputStream(result); 
   String excelFormat = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
   FileTransfer dwrExcelFile = new FileTransfer("excel.xlsx", excelFormat, myInputStream);
   return dwrExcelFile;
}

//Javascript side:

function downloadExcelFile() {
  dwr.engine.setTimeout(59000);
  var params = <params_to_send>;
  <Java_class>.getExcel(params, {callback:function(dataFromServer) {
    downloadExcelCallback(dataFromServer);
  }});
}

function downloadExcelCallback(data) {
   dwr.engine.openInDownload(data);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!