网上关于java文件下载的代码不计其数,我在使用spring做文件下载时,开始也是使用的普通的下载方式,但是遇到一个问题,后台老是报错:java.net.SocketException: Connection reset by peer: socket write error,虽然文件是能下载,但是一下载就会报如上错误,google上一大片关于该问题的讨论,但究其原因,还得根据自身项目情况而言,网上的解决办法都没能阻止该错误的出现。我也因为无法确定到底是什么原因导致的,故改用另一种方式下载了,以下是大致源码:
- public String downLoadSongFile(HttpServletResponse response)
- {
- InputStream fis = null;
- try
- {
- String songName = "左右为难-蔡淳佳.mp3";
- String filePath = "d:/";
- File file = new File(filePath + songName);
- if (!file.exists())
- {
- return null;
- }
- // 以流的形式下载文件
- fis = new BufferedInputStream(new FileInputStream(filePath));
- doDownload(fis, response, songName);
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- finally
- {
- if (null != fis)
- {
- try
- {
- fis.close();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- }
- return null;
- }
- private void doDownload(InputStream inputStream, HttpServletResponse response, String songName) throws IOException
- {
- response.setContentType("application/" + resolveContentType(songName));
- response.setHeader("Content-Disposition", "attachment;" + "filename=" + songName);
- FileCopyUtils.copy(inputStream, response.getOutputStream());
- }
- private String resolveContentType(String fileName)
- {
- try
- {
- return fileName.substring(fileName.lastIndexOf(".") + 1);
- }
- catch (StringIndexOutOfBoundsException e)
- {
- return "";
- }
- }
这里的代码和常规用法的主要是以下这句代码:
FileCopyUtils.copy(inputStream, response.getOutputStream());
在上面的代码中,我们并没有显式地向页面输出内容,而是通过上面这句代码完成的,通过这种方式,终于解决了上面那个讨厌的错误的身影!