Home > Blockchain >  How can I rename the response from an http request?
How can I rename the response from an http request?

Time:10-06

I have a relatively simple Java/Tomcat requirement but I can't figure out how to implement it.

I have an HTTPS POST request into a specific server URL, call it /myserver/somecontroller.do.

The controller method correctly returns an Excel document with a mime type of application/vnd.ms-excel.

This all works fine. The problem is that the response gets downloaded on the client computer with the name somecontroller.do instead of something that Excel understands, like myspreadsheet.xls.

So when the user clicks the file to open it, they get an ugly error message instead of the spreadsheet they were expecting, and I get a trouble ticket in my inbox.

They could rename the file, but the optimal solution is to have the system name the file correctly.

How can I modify the HTTPServletResponse parameters so that it understands it's sending a document called myspreadsheet.xls instead of somecontroller.do?

Some cleaned-up example code:

// Returns a spreadsheet, but it's called "somethingelse.do" instead of 
// "somethingelse.xls"


@RequestMapping(value="/something/somthingelse.do", method=RequestMethod.POST)
    public String doSomething(@ModelAttribute ReportModel reportModel, BindingResult bindResult,HttpServletResponse response,Model model) throws Exception{
    Workbook reportObj = ReportService.generateExcel(ReportService.getReportData(reportModel.getReportParameters()));
    response.setContentType("application/vnd.ms-excel");
    OutputStream out = response.getOutputStream();
    HSSFWorkbook workbook = (HSSFWorkbook) reportObj;
    workbook.write(out);
    out.flush();
    return SomeViewMapping.VIEW_SOMETHING.getViewName();
}

CodePudding user response:

You need one more header. Something like:

response.setHeader("Content-Disposition", "attachment; filename=myspreadsheet.xls");
  • Related