SpringMVC文件上传与下载

文件的上传:
	1.配置xml 
		<bean id="multipartResolver" class="springframework.web.multipart.commons.CommonsMultipartResolver">
			<property name="defaultEconding" value="utf-8">			
		</bean>
	2.页面
		<form action="" method="post" enctype="multipart/form-data">
			文件<input type="file"name="file">
			<input type="submit" type="上传">
		</form>
	3.创建controller
		public String upload(@RequestParam("file") CommonsMultipartFile file,httpSession session){
			system.out.println(file.getName);			上传的名字
			system.out.println(file.getOriginalFilename());		上传的文件名字
			system.out.println(file.getContextType());		上传文件的类型
			system.out.println(file.getSize());			上传文件的大小
			
			ServletContext applicstion=session.getServletContext();		
			String uploaddir =applicstion.getRealPath("/WEB-INF/upload");
			file.transferTo(new File(uploaddir,file.getOriginaFilename()));
			return "redirect: upload ";
		}

文件的下载:	
	1.页面
		<a href="${pageContext.request.contextPath}/download "></a>	
	2.创建controller
		public String download(httpServletResponse response,httpSession session){
			
	     先读	inputStream in=null;    
	     再写	outputStream out=null;
显示下载后的文件名字    Response.setHeader("content-disosition","attachment;filename=下载文件的名字".getbytes("utf-8"),"iso8859-1");

			ServletContext applicstion=session.getServletContext();
	文件所在路径	in=new FileInputStream(application.getRealPath("file/abc.text"));
			out=new FileOutputStream();
				
			byte[] b= new byte[2048];	
			int n;
			while((n=in.read(b))!=-1){
				out.writer(b,0,n);	
			}
			if(in!=null){
				in.close();	
			}
			if(out!=null){
				in.close();	

			}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值