ssm实现文件上传与下载

jar包或者pom文件可以搜一下

前台里请求格式得是


enctype="multipart/form-data" method="post">
 <form id="documentForm" name="documentForm" action="${pageContext.request.contextPath}/document/addDocument.do" enctype="multipart/form-data" method="post">


定义元素里必须有
MultipartFile file

	private Integer id;
	private String title;
	private String filename;
	private String remark;
	private Date create_date;
	private User user;
	private MultipartFile file;

配置文件

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding">
			<value>UTF-8</value>
		</property>
		<property name="maxUploadSize">
			<value>2000000</value>
		
		</property>
	</bean> 

后台springmvc接收

@RequestMapping("addDocument.do")
	public String addDocument(Document docunment, HttpSession session, Model model){
	//上传文件的路径
		String path = session.getServletContext().getRealPath("/upload");
		System.out.println(path);
		
	//文件名	
		String filename = docunment.getFile().getOriginalFilename();
	//获取文件	上传到指定路径	文件 如 c/a.txt,File.separator相当于"/"
		try {
			docunment.getFile().transferTo(new File(path+File.separator + filename));
			docunment.setFilename(filename);
			
			User user = (User) session.getAttribute("user");
			docunment.setUser(user);
		} catch (IllegalStateException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		documentService.addDocument(docunment);
		return "redirect:/document/query.do";
		
	}
dao层访问数据库
<insert id="insertDocument">
		insert into document_inf (title,filename, remark, user_id )
		values( #{title}, #{filename}, #{remark}, #{user.id} )
	</insert>





文件下载:先查询后完成下载

  @RequestMapping("/upload.do")  
	      public void down(int id, HttpServletRequest request,HttpServletResponse response) throws Exception{ 
				Document document =	documentService.findDocumentById(id);
				String filename = document.getFilename();
	         //模拟文件,myfile.txt为需要下载的文件  
	        	String fileName = request.getSession().getServletContext().getRealPath("upload")+File.separator+ filename;  
	        //获取输入流  
	        	InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));  
	        //假如以中文名下载的话  
	       /*  String filename = "下载文件.txt";  */
	       //转码,免得文件名中文乱码  
	        	String downloadFilename = processFileName(request,fileName);
	        	//filename = new String(filename.getBytes("UTF-8"),"iso8859-1");
	       // filename = URLEncoder.encode(fileName,"UTF-8");  
	       //设置文件下载头  
	        response.addHeader("Content-Disposition", "attachment;filename=" + downloadFilename);    
	       //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型    
	        	response.setContentType("multipart/form-data");   
	        	BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());  
	        	int len = 0;  
	       while((len = bis.read()) != -1){  
	            out.write(len);  
	            out.flush();  
	        }  
	       out.close();  
	    }  


//各个浏览器处理下载后的文件名乱码问题

 public static String processFileName(HttpServletRequest request, String fileNames) {  
	       String codedfilename = null;  
	       try {  
	           String agent = request.getHeader("USER-AGENT");  
	           if (null != agent && -1 != agent.indexOf("MSIE") || null != agent  
	                   && -1 != agent.indexOf("Trident")) {// ie  
	  
	               String name = java.net.URLEncoder.encode(fileNames, "UTF8");  
	  
	               codedfilename = name;  
	           } else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等  
	  
	  
	               codedfilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");  
	           }  
	       } catch (Exception e) {  
	           e.printStackTrace();  
	       }  
	       return codedfilename;  
	   }  







SSM框架文件上传下载可以通过以下步骤实现: 1. 文件上传: - 在前端页面上添加文件选择框和上传按钮; - 在后端控制器中添加处理文件上传的方法; - 在方法中使用SpringMVC的MultipartFile类获取上传的文件; - 对文件进行处理并保存到服务器上。 示例代码: ```java @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public String upload(MultipartFile file) { // 获取上传的文件名 String fileName = file.getOriginalFilename(); // 处理文件并保存到服务器上 // ... return "上传成功!"; } ``` 2. 文件下载: - 在前端页面上添加下载按钮; - 在后端控制器中添加处理文件下载的方法; - 在方法中使用SpringMVC的ResponseEntity类将文件发送到客户端。 示例代码: ```java @RequestMapping(value = "/download", method = RequestMethod.GET) public ResponseEntity<byte[]> download() throws IOException { // 获取要下载的文件 File file = new File("文件路径"); // 将文件转换为字节数组 byte[] body = FileUtils.readFileToByteArray(file); // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=" + file.getName()); HttpStatus statusCode = HttpStatus.OK; ResponseEntity<byte[]> response = new ResponseEntity<>(body, headers, statusCode); return response; } ``` 以上是简单的文件上传下载实现方法,具体实现还需要根据具体需求进行调整。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值