spring MVC文件的上传和下载

27 篇文章 0 订阅
/** 文件上传
	  * @author:zzq
	  * @createTime:2015-3-23
	  */
	@RequestMapping(value="/upload.html")
	public String upload(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
		String bookName = null;
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
			if(multipartResolver.isMultipart(request)){
				MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
				Iterator<String> iterator = multipartRequest.getFileNames();//
				while(iterator.hasNext()){
					MultipartFile file = multipartRequest.getFile((String)iterator.next());
					if(file != null){
						bookName = file.getOriginalFilename();
						 String path = request.getSession().getServletContext().getRealPath("/upload/"+bookName);
						 File localFile = new File(path);
						if (!localFile.exists()) {
							localFile.mkdirs();
						}
						file.transferTo(localFile);
					}
				}
			}
		
			//入库
			EntrustBook book = new EntrustBook();
			book.setBookName(bookName);
			entrustBookService.save(book);
			
			return "/contracts/upload_ok";
	}
	
	
	/**
	  * 文件下载
	  * @author:zzq
	  * @createTime:2015-3-24
	  * @param fileName
	  * @param request
	  * @param response
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping("/download.html")
	 public String download(Integer id,HttpServletRequest request, HttpServletResponse response)throws Exception {
	  request.setCharacterEncoding("UTF-8");
	  EntrustBook book = entrustBookService.find(id);
	  BufferedInputStream bis = null;  //从文件中读取内容
	  BufferedOutputStream bos = null; //向文件中写入内容
	  
	  //获得服务器上存放下载资源的地址
	  String ctxPath = request.getSession().getServletContext().getRealPath("/upload/");
	  //获得下载文件全路径
	  String fileName = book.getBookName();
	  String downLoadPath = ctxPath +"/"+ fileName;
	  System.out.println(downLoadPath);
	  //如果文件不存在,退出
	  File file = new File(downLoadPath);
	  if(!file.exists()){
	   return null;
	  }
	  try {
	   //获得文件大小
	   long fileLength = new File(downLoadPath).length();
	   System.out.println(new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
	   response.setContentType("text/html;charset=utf-8"); //设置相应类型和编码
	   response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "ISO-8859-1"));
	   response.setHeader("Content-Length", String.valueOf(fileLength));
	   
	   bis = new BufferedInputStream(new FileInputStream(downLoadPath));
	   bos = new BufferedOutputStream(response.getOutputStream());
	   //定义文件读取缓冲区
	   byte[] buff = new byte[2048];
	   int bytesRead;
	   //把下载资源写入到输出流
	   while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
	    bos.write(buff, 0, bytesRead);
	   }
	  } catch (Exception e) {
	   e.printStackTrace();
	  } finally {
	   if (bis != null)
	    bis.close();
	   if (bos != null)
	    bos.close();
	  }
	  return "/contracts/download_ok";
	 }

	

 

@RequestMapping(value="/toUpload.html")
	public String toUpload(Model model){
		return "/contracts/upload";
	}
	
	@RequestMapping(value="/toDownload.html")
	public String toDownload(Model model){
	
		return "/contracts/download";
	}


文件下载主要是把它的id也一起显示,适合选择下载。上传一起把name一起传到数据库去。


***************

jsp页面:

           

<li><a class="upload" href="${ctx}/contracts/toUpload.html"  rel="items" ><span>文件上传</span></a></li>
   <li><a class="download" href="${ctx}/contracts/downloadBook.html"  enctype="multipart/form-data" rel="items" ><span>文件下载</span></a></li>


upload.jsp

<form action="${ctx}/contracts/upload.html"  enctype="multipart/form-data" method="post">
  		<input name="fileId" type="hidden" value="${file.fileId}"/>
  		<input name="contractsName" class="required" type="text" size="30" value="${file.fileName}" alt="请输入合同名称"/>
  		<input type="file" name="file" multiple="true">
  		
  		<input type="submit"  value="上传">

     	</form>


 

download.jsp


 

 <c:forEach items="${books}" var="entity">
    <a href="${ctx}/contracts/download.html?id=${entity.bookId}">${entity.bookName}</a></br>
   </c:forEach>


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值