Java 实现下载

效果就是点击就可以下载到本机。

  • 前台代码示例
  • 后台代码示例

前台代码示例

<a target='_self' href='../downTask/downloadFileToLocal?fileName=59.csv' >

后台代码示例

@RequestMapping(value = "/downloadFileToLocal", method = RequestMethod.GET)
    public void downloadFileToLocal(String fileName,HttpServletRequest request,  HttpServletResponse response) throws IOException {
                response.setCharacterEncoding("utf-8");
                response.setContentType("multipart/form-data");
                response.setHeader("Content-Disposition", "attachment;fileName="
                        + fileName);
                OutputStream os = response.getOutputStream();
                try {
                    String path = Helper.getAppPath();
                    log.debug("========="+path);
                    InputStream inputStream = new FileInputStream(new File(path
                            + File.separator + fileName));
                    byte[] b = new byte[2048];
                    int length;
                    while ((length = inputStream.read(b)) > 0) {
                        os.write(b, 0, length);
                    }
                    inputStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally{
                     os.close();
                }
        }

注:我这个框架是用的SpringMVC,自行修改吧。

发布了46 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/kingbox000/article/details/50450713
今日推荐