在网页上,如果我们的超链接的地址对应的是一个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;
}
}
}
}