spring框架下的文件(常用的文件为excel)下载总结

本文分享了作者在项目中实现Excel上传下载功能的经验,详细介绍了本地和远程文件下载的方法,包括前端JS请求方式与后端Java处理逻辑。

在项目中做了好几次excel上传下载的功能,还算比较有心得,这里我分成两节来说,第一节专门说下载,下一节专门说处理上传的excel信息。

文件下载按照资源文件的储存地方分为两种:第一种为本地或者本项目中的文件,第二种为远程文件。资源文件所处位置不同,前台的请求js也不相同。这里先看前台js的不同。然后再看后台java代码的区分。

1.前台js比较

1.1 下载本地/本项目中的文件。

<script type="text/javascript">
    function downloadFile(){
        window.location.href=basepath+"/epress/downloadExcel";
    }
</script>

1.2 下载远程资源文件

function dataDownload(){
    var elemIF=document.createElement("iframe");
    elemIF.src=basepath+"datadownload/getDownload?";
    elemIF.style.display="none";
    document.body.appendChile(elemIF);
}

2.后台java代码

一般页面请求到controller层就执行下载返回了,不在走service层。当然如果有啥业务牵扯还是具体问题具体解决。

2.1 下载本地、本项目,本工程中的文件(一般下载excel模板)。如下:

这里写图片描述

项目整体结构及excel模板位置webap/excelModel/下:

这里写图片描述

//下载模板
    @RequestMapping("/downloadModel")
    public void downloadExcel(HttpServletRequest request,HttpServletResponse response){
        String path=request.getSession().getServletContext().getRealPath("excelModel");
        path=path.replace("\\", "/");
        if(!path.endsWith("/")){
            path+="/";
        }
        File file=new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        String fileName="基金信息导入模板.xlsx";
        String strFileName=path+fileName;
        FileUtils.downloadFiles(response, strFileName);
    }

**********对应工具类: FileUtils.downloadFiles代码*******
/**
     * 【本地、本应用】文件下载
     * 
     * @param response
     * @param filePath 文件路径
     */
    public static void downloadFiles(HttpServletResponse response,
            String filePath) {
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        FileInputStream fs = null;
        BufferedInputStream buff = null;
        OutputStream myout = null;

        try {
            File file = new File(filePath.trim());
            if (file.exists()) {
                String fileName = file.getName();
                fs = new FileInputStream(file);
                response.addHeader(
                        "Content-Disposition",
                        "attachment;filename="
                                + URLEncoder.encode(fileName, "UTF-8"));
                buff = new BufferedInputStream(fs);
                byte[] b = new byte[1024];
                long k = 0;
                myout = response.getOutputStream();
                while (k < file.length()) {
                    int j = buff.read(b, 0, 1024);
                    k += j;
                    myout.write(b, 0, j);
                }
                buff.close();
            } else {
                PrintWriter os = response.getWriter();
                os.write("文件不存在");
                os.close();
            }
            if (myout != null) {
                myout.flush();
                myout.close();
            }
            if (fs != null) {
                fs.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (myout != null) {
                try {
                    myout.flush();
                    myout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

2.2 远程文件下载对应controller层代码

@RequestMapping("/getDownload")
public void getDownloadData(HttpServletRequest request, HttpServletResponse response){
    //请求的远程文件的地址
    Strng fileUrl="http://111.98.34.182/voice/Moo/text.txt";
    FileUtils.getDownloadData(request,response,fileUrl);
}

*************对应的下载工具类***************
/**
     * 【远程】文件下载
     * 
     * @param request
     * @param response
     * @param fileUrl
     *            请求下载的远程文件路径/地址
     */
    public void getDownloadData(HttpServletRequest request,
            HttpServletResponse response, String fileUrl) {
            HttpURLConnection urlCon = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            URL romoteUrl = new URL(fileUrl);
            urlCon = (HttpURLConnection) romoteUrl.openConnection();
            urlCon.setConnectTimeout(10000);
            urlCon.setReadTimeout(30000);

            is = urlCon.getInputStream();
            response.reset();

            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader(
                    "Content-Disposition",
                    "attachment;filename="
                            + new String((System.currentTimeMillis() + fileUrl.substring(fileUrl.lastIndexOf("/"))).getBytes(), "iso-8859-1"));
            bis=new BufferedInputStream(is);
            bos=new BufferedOutputStream(response.getOutputStream());

            byte[] buff=new byte[2048];
            int bytesRead;
            while(-1 !=(bytesRead=bis.read(buff, 0, buff.length))){
                bos.write(buff,0,bytesRead);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                is.close();
                bis.close();
                bos.close();
                urlCon.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

万米高空

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值