Return xml file from spring MVC controller

前端 未结 1 1771
北荒
北荒 2021-01-12 09:13

I have tried a lot to return a file from the controller function.

This is my function:

@RequestMapping(value = \"/files\", method = RequestMethod.GE         


        
相关标签:
1条回答
  • 2021-01-12 10:08

    EDIT 2: First of all - see edit 1 in the bottom - that't the right way to do it. However, if you can't get your serializer to work, you can use this solution, where you read the XML file into a string, and promts the user to save it:

    @RequestMapping(value = "/files", method = RequestMethod.GET)
    public void saveTxtFile(HttpServletResponse response) throws IOException {
    
        String yourXmlFileInAString;
        response.setContentType("application/xml");
        response.setHeader("Content-Disposition", "attachment;filename=thisIsTheFileName.xml");
    
        BufferedReader br = new BufferedReader(new FileReader(new File(YourFile.xml)));
        String line;
        StringBuilder sb = new StringBuilder();
    
        while((line=br.readLine())!= null){
            sb.append(line);
        }
    
        yourXmlFileInAString  = sb.toString();
    
        ServletOutputStream outStream = response.getOutputStream();
        outStream.println(yourXmlFileInAString);
        outStream.flush();
        outStream.close();
    }
    

    That should do the job. Remember, however, that the browser caches URL contents - so it might be a good idea to use a unique URL per file.

    EDIT:

    After further examination, you should also just be able to add the following piece of code to your Action, to make it work:

    response.setContentType("text/plain");
    

    (Or for XML)

    response.setContentType("application/xml");
    

    So your complete solution should be:

    @RequestMapping(value = "/files", method = RequestMethod.GET)
    @ResponseBody public FileSystemResource getFile(HttpServletResponse response) {
        response.setContentType("application/xml");
        return new FileSystemResource(new File("try.xml")); //Or path to your file 
    }
    
    0 讨论(0)
提交回复
热议问题