文件的上传和下载--存为二进制文件

       在实际项目中,上传文件的保存,一般由两种形式:   文件存为二进制,   只保存文件在 应用服务器中的路径。

本文 主要讲解  文件保存为二进制。使用的数据库为  Mysql.  使用的框架  springmvc+hibernate


1.文件上传及接收

1.1文件的上传

这里只贴出jsp中部分代码。只需关注红色字体的地方。
enctype="multipart/form-data">
${title}


/> 请注意上传合同的正确性 上传成功 请选择上传文件所在路径! 该文件名已存在!




1.2文件的接收

下面代码只需关注文件类型便可。
@RequestMapping(value = {"/user/","url---uploadcontractfile.htm"},method = RequestMethod.POST)
	public ModelAndView upload(String number,@RequestParam("file") MultipartFile file, String type,
	HttpSession session,HttpServletRequest request) throws IllegalAccessException, InvocationTargetException {	
		User user=(User)session.getAttribute("user");
		if(file==null||file.getOriginalFilename().equals("")){
			ModelAndView mv=new ModelAndView();
			mv.addObject("errorInfo","请选择上传文件所在路径!点击返回!");
			mv.setViewName("/user/project/contract/error");
			mv.addObject("id",number);
			return mv;
		}
		else if(!(file.getOriginalFilename().endsWith(".pdf")|file.getOriginalFilename().endsWith(".jpg")
				|file.getOriginalFilename().endsWith(".zip")|file.getOriginalFilename().endsWith(".rar")
				|file.getOriginalFilename().endsWith(".png")|file.getOriginalFilename().endsWith(".jpeg")
				)){
			ModelAndView mv=new ModelAndView();
			mv.addObject("errorInfo","请选择PDF、jpg、zip、rar、png、jpeg格式文件!点击返回!");
			mv.setViewName("/user/project/contract/error");
			mv.addObject("id",number);
			return mv;
		}
		try{
			contractService.upload(user, file,number,request);
			ModelAndView mv = new ModelAndView();
			mv.setViewName("redirect:contractprojectundo.htm");
			return mv;			
		}
		catch(IOException e){
			ModelAndView mv=new ModelAndView();
			mv.addObject("errorInfo","error:"+e.getMessage());
			mv.setViewName("/user/project/contract/error");
			return mv;
		}
	}

2.文件保存及下载

2.1文件的保存

文件保存在 contract中。

ublic void upload(User user,MultipartFile file,String number,HttpServletRequest request) 
        throws IOException, IllegalAccessException, InvocationTargetException{
	Contract contract = this.getContract(Long.parseLong(number));
	String fileName=file.getOriginalFilename();
	contract.setContractFileName(fileName);
	InputStream fis = file.getInputStream();
	byte[] buffers = new byte[(int) file.getSize()];
	fis.read(buffers);   
	Session session = hibernateTemplate.getSessionFactory().openSession(); 
     LobHelper lobHelper = session.getLobHelper();   
	Blob blob = lobHelper.createBlob(buffers);
	contract.setContractFile(blob);
	contract.setContractStatus("合同已上传");
	hibernateTemplate.update(contract);
	hibernateTemplate.flush();
}	

2.2 文件的下载

public void download(Long cid,HttpServletResponse response) 
      throws IOException, SQLException {
	// TODO Auto-generated method stub
	Contract contract =this.getContract(cid);
	String fileName=contract.getContractFileName();
	//可以通过以下方法得到后缀
//	int spiltIndex = fileName.indexOf(".");
//	String startName = fileName.substring(0, spiltIndex);
//	String endName = fileName.substring(spiltIndex+1);
		
	response.setCharacterEncoding("UTF-8"); //为了解决中文
	response.setHeader("Content-Disposition", "attachment; filename="
			+ URLEncoder.encode(fileName, "UTF-8"));
	InputStream stream;
	if(contract.getContractFile()!=null){
	   stream = contract.getContractFile().getBinaryStream();
	 }else{
		stream = null;
	   }
	if(stream!=null){
	  ServletOutputStream fs= response.getOutputStream();
	  byte[] buffer =new byte[1024*1024];    
	      int byteread = 0;    
	      while ((byteread=stream.read(buffer))!=-1) {   
		       bytesum+=byteread;   
		       fs.write(buffer,0,byteread);   
		       fs.flush();   
		     } 
		      fs.close(); 
		}else{
	   response.sendRedirect("contractdownloaderror.htm?cid="+cid);
	    this.hibernateTemplate.flush();
		}
	}  










你可能感兴趣的:(java,java,文件上传,spring,mvc,jsp,httpSession)