• SpringMVC中文件的上传(上传到服务器)和下载问题(二)--------下载


    一、建立一个简单的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下导入一首歌。如图:

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

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

  • 相关阅读:
    有用的java工具
    AOP在大规模软件开发项目中的应用(图)
    java并发编程实践笔记
    深入JVM系列(三)之类加载、类加载器、双亲委派机制与常见问题
    JVM相关问答
    软件架构设计的六大原则
    JVM 运行时数据区域
    JVM 类加载过程
    JVM 垃圾回收算法
    Memcached内存分配优化及使用问题
  • 原文地址:https://www.cnblogs.com/of-fanruice/p/7424987.html
Copyright © 2020-2023  润新知