zoukankan      html  css  js  c++  java
  • 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下导入一首歌。如图:

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

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

  • 相关阅读:
    Eclipse集成weblogic教程
    Weblogic项目部署教程
    Eclipse导出WAR包
    Eclipse集成Tomcat教程
    Eclipse错误:The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path
    Eclipse导入Oracle/MySQL数库驱动包教程
    Java连接Oracle/MySQL数据库教程
    Oracle常用表和常见操作命令
    VMware如何进入安全模式
    VMware进入BIOS
  • 原文地址:https://www.cnblogs.com/of-fanruice/p/7424987.html
Copyright © 2011-2022 走看看