txt,图片等实现默认下载而不是打开图片

8 篇文章 0 订阅

在网页上,如果我们的超链接的地址对应的是一个jpg文件,txt文件等,点击链接时,浏览器默认的是打开这些文件而不是下载,那么如何才能实现默认下载呢。
如果需要实现默认点击弹出下载框,需要特殊处理
前端代码:

function downloadFile(docUrl, fileName) {
        window.location.href = "<%=basePath%>ajax/downloadFile?url=" + docUrl + "&filename=" + fileName;
    }

<a href="javascript:void(0);" onclick="downloadFile('docUrl','fileName')"/>

后端代码:

@GetMapping(produces = {"text/html;charset=UTF-8"})
    public void downloadFile(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "url") String urlStr, @RequestParam(value = "filename") String fileName)
        throws IOException
    {
        URL url = new URL(urlStr);
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        ServletOutputStream out = null;
        try
        {
            conn = (HttpURLConnection)url.openConnection();
            inputStream = conn.getInputStream();
            out = response.getOutputStream();
            IOUtils.copy(inputStream, out);
            out.flush();
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (null != inputStream)
            {
                try
                {
                    inputStream.close();
                }
                catch (IOException e)
                {
                    throw e;
                }
            }
            if (null != out)
            {
                try
                {
                    out.close();
                }
                catch (IOException e)
                {
                    throw e;
                }
            }
            if (null != conn)
            {
                try
                {
                    conn.disconnect();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值