1. 程式人生 > >SpringMVC中文件的上傳(上傳到服務器)和下載問題(二)--------下載

SpringMVC中文件的上傳(上傳到服務器)和下載問題(二)--------下載

cat exc stream log trac close pri page fin

一、建立一個簡單的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下導入一首歌。如圖:

技術分享

四、下面運行我們的程序。

然後點擊超鏈接,瀏覽器就會下載這首歌,然後你就能在你下載的位置找到這首歌並且可以正常的聽!

SpringMVC中文件的上傳(上傳到服務器)和下載問題(二)--------下載