java - jsp+springMVC实现文件下载的时候后台抛出getOutputStream()异常
迷茫
迷茫 2017-04-18 10:53:58
0
1
529

使用JSP+springMVC框架做的web平台,在做文件下载的时候,遇到这样的问题:

文件下载部分的代码是这样写的:

@RequestMapping("/ModelDownload{id}")
public String ModelDownLoad(@PathVariable int id, HttpServletResponse response){
    String fileName = "download.txt"; 
    String filePath = "D:\\";
    String modelName = new ModelService().getModelById(id).getModelName();
    System.out.println(modelName);
    response.reset();
    response.setContentType("application/x-download");
    response.addHeader("Content-Disposition", "attachment;filename="+fileName);//重新设置响应头文件字段,设置下载文件的文件名
    OutputStream OutputStream = null;
    FileInputStream fileInputStream = null;
    try {
        OutputStream = response.getOutputStream();
        fileInputStream = new FileInputStream(filePath+fileName);
        byte[] buffer = new byte[1024*10];//设置文件大小上限为10M
        for (int read; (read = fileInputStream.read(buffer)) != -1;){
            OutputStream.write(buffer,0,read);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println(e.toString());
    }
    finally{
        try {
            fileInputStream.close();
            OutputStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return "success";
}

百度了很多,几乎都是说在JSP上使用out对象进行clear()和close()操作的,根本没有针对后台操作遇到的相同问题的解决方案,求大神指导。

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
洪涛

Problem solution: Just change the return type of the method to void.
The reason for the problem may be that when the return type is String, click the download button and the download page will pop up. At this time, the background code is interrupted. If not, just close() ;

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!