首页 > 技术文章 > SpringMVC中文件的上传(上传到服务器)和下载问题(二)--------下载

of-fanruice 2017-08-24 19:54 原文

一、建立一个简单的jsp页面。

      我们在建好的jsp的页面中加入一个超链接:<a href="${pageContext.request.contextPath}/download">下载</a>

二、在控制层写入以下代码:

 

	@RequestMapping("/download")
	public ResponseEntity<byte[]> String(HttpServletRequest request) throws IOException{
		byte[] size=null;
		ServletContext servletContext =request.getServletContext();
		String filename="nobody.mp3";
		String path=servletContext.getRealPath("/WEB-INF/"+filename);
		File file=new File(path);
		ResponseEntity<byte[]> response=null;
		InputStream in=null;
		try {
			in= new FileInputStream(file);
			size= new byte[in.available()];
			in.read(size);
			HttpHeaders headers= new HttpHeaders();
			filename=new String(filename.getBytes("gbk"),"iso8859-1");
			headers.add("Content-Disposition", "attachment;filename="+filename);
			HttpStatus status=HttpStatus.OK;
			response=new ResponseEntity<byte[]> (size,headers,status);
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		}finally{
			in.close();
		}
		return response;
		
	}

 

三、在服务器指定的位置加入你需要下载的文件。这里我们在服务器里WEB-INF下导入一首歌。如图:

四、下面运行我们的程序。

         然后点击超链接,浏览器就会下载这首歌,然后你就能在你下载的位置找到这首歌并且可以正常的听!

 

推荐阅读