在網頁上,如果我們的超鏈接的地址對應的是一個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;
}
}
}
}