SpringMVC基础及实例(二)文件上传简单实例

springMVC提供了两种文件上传的方式,一种是自己写输入到本地,另一种是借助springMVC封装好的MultipartHttpServletRequest上传文件。


上传文件所需的两个jar包:

   com.springsource.org.apache.commons.fileupload

    com.springsource.org.apache.commons


注意:

1.上传文件无论用什么框架都需要用到“enctype”属性

2.必须采用method方式


配置文件:

1.web.xml

  <servlet>
  	<servlet-name>springMVC</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  		<init-param>
  			<param-name>contextConfigLocation</param-name>
  			<param-value>classpath*:config/springAnnotation-servlet.xml</param-value>
  		</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  
 	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<!-- encoding filter for jsp page -->
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
  
    <servlet-mapping>
  	<servlet-name>springMVC</servlet-name>
  	<url-pattern>/</url-pattern>
  </servlet-mapping>

2. springAnnotation-servlet.xml文件

  <!-- 注解扫描包 -->
    <context:component-scan base-package="com.tgb.web.controller.annotation" />
    <!-- 开启注解 -->    
    <mvc:annotation-driven/>    

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <property name="defaultEncoding" value="utf-8" />
             <!-- 指定所上传文件的总大小。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
          <property name="maxUploadSize" value="10485760000" />
          <property name="maxInMemorySize" value="40960" />
    </bean>


CommonsMultipartResolver允许设置的属性有:

  • defaultEncoding:表示用来解析request请求的默认编码格式,当没有指定的时候根据Servlet规范会使用默认值ISO-8859-1。当request自己指明了它的编码格式的时候就会忽略这里指定的defaultEncoding。
  • uploadTempDir:设置上传文件时的临时目录,默认是Servlet容器的临时目录。
  • maxUploadSize:设置允许上传的最大文件大小,以字节为单位计算。当设为-1时表示无限制,默认是-1。
  • maxInMemorySize:设置在文件上传时允许写到内存中的最大值,以字节为单位计算,默认是10240。


3. jsp页面:

<body>
	<h>添加用户</h>
	<form name="userForm" action="/springMVC7/file/upload2" method="post" enctype="multipart/form-data" >
		选择文件:<input type="file" name="file">
		<input type="submit" value="上传" >
	</form>
</body>

4.方式一:手动输入本地文件

@RequestMapping("/upload1")
	public String addUser(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException{
		输出file名称
		System.out.println("fileName---->" + file.getOriginalFilename());
		
		if(!file.isEmpty()){
			try {
				//将文件放到D盘的根目录 
				FileOutputStream os = new FileOutputStream("D:/" + new Date().getTime() + file.getOriginalFilename());
				//获取输入流
				InputStream in = file.getInputStream();
				//写文件
				int b = 0;
				while((b=in.read()) != -1){
					os.write(b);
				}
				os.flush();
				os.close();  
				in.close(); 
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "/success";
	}


4.方式二:采用封装好的MultipartHttpServletRequest上传文件

	@RequestMapping("/upload2")
		public String upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
			
			//定义一个解释器,解析request,拿到springMVC初始化的上下文,解析上下文
			CommonsMultipartResolver multipartResolver  = new CommonsMultipartResolver(request.getSession().getServletContext());
			
			//判断request是否为map类型数据
			if(multipartResolver.isMultipart(request)){
				//转换SpringMVC封装好的文件类型
				MultipartHttpServletRequest  multiRequest = (MultipartHttpServletRequest)request;
				//定义迭代器获取文件名称
				Iterator<String>  iter = multiRequest.getFileNames();
				while(iter.hasNext()){
						//获取文件,MultipartFile定义文件类型
						MultipartFile file = multiRequest.getFile((String)iter.next());
					if(file != null){
						//定义输出文件名称
						String fileName = "demoUpload" + file.getOriginalFilename();
						//定义输出路径
						String path = "D:/" + fileName;		
						//new 一个文件类型
						File localFile = new File(path);
						//将上传文件转到本地文件
						file.transferTo(localFile);
					}
					
				}			
			}
			return "/success"; //返回成功页面
		}	
	}


在使用第二种方式时,需要在配置文件springAnnotation-servlet.xml中配置MultipartResolver处理器。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
Spring MVC是一个基于Java的开源框架,用于构建Web应用程序。它提供了一种模型-视图-控制器(MVC)的架构模式,用于将应用程序的不同部分分离开来,以实现更好的可维护性和可扩展性。 下面是一个简单的Spring MVC上传下载的实例: 1. 配置文件: 首先,在Spring MVC的配置文件中添加以下配置: ```xml <!-- 配置文件上传 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10485760"/> <!-- 设置最大上传文件大小为10MB --> </bean> ``` 2. 控制器类: 创建一个控制器类,用于处理上传和下载请求。以下是一个示例: ```java @Controller public class FileController { @RequestMapping(value = "/upload", method = RequestMethod.POST) public String uploadFile(@RequestParam("file") MultipartFile file) { // 处理文件上传逻辑 if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); // 保存文件到服务器或者其他操作 return "redirect:/success"; // 上传成功后跳转到成功页面 } catch (IOException e) { e.printStackTrace(); } } return "redirect:/error"; // 上传失败后跳转到错误页面 } @RequestMapping(value = "/download", method = RequestMethod.GET) public ResponseEntity<Resource> downloadFile() { // 处理文件下载逻辑 // 构建文件资源对象 Resource fileResource = new FileSystemResource("path/to/file"); // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.txt"); // 返回文件资源和响应头 return ResponseEntity.ok() .headers(headers) .contentLength(fileResource.contentLength()) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(fileResource); } } ``` 3. 前端页面: 在前端页面中添加上传和下载的表单和按钮。以下是一个简单的示例: ```html <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上传" /> </form> <a href="/download">下载文件</a> ``` 这是一个简单的Spring MVC上传下载的实例。你可以根据实际需求进行修改和扩展。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值