SpringMVC环境下导出文件

来源:互联网 发布:以撒的结合yum heart 编辑:程序博客网 时间:2024/05/22 12:52

很简单的代码,不多说,直接上代码

这是后台代码

@RequestMapping("/download.do")    public String download(int id, HttpServletRequest request,            HttpServletResponse response) {User user = userService.getById(id);        response.setCharacterEncoding("utf-8");        response.setContentType("multipart/form-data");        response.setHeader("Content-Disposition", "attachment;fileName="                +"ldk.png");                String path = user.getQrPath();        //获取数据//########################下载文件begin########################        try {            InputStream is = new FileInputStream(new File(path));            OutputStream os = response.getOutputStream();            byte[] b = new byte[2048];            int length;            while ((length = is.read(b)) > 0) {                os.write(b, 0, length);            }              // 这里主要关闭。            os.close();             is.close();        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }      //########################下载文件end########################            //  返回值要注意,要不然就出现下面这句错误!            //java+getOutputStream() has already been called for this response        return null;    } 

前端只需要一个链接就可以了

<input type="button" onclick="window.location.href='${ctx}/users/download.do?id=${user.id}'" value="导出"/>
结果就是



0 0
原创粉丝点击