spring mvc-文件上传

            在文件上传时,我们需要用到文件上传解析器,其实,它并不陌生,只是对httpServletRequest的一个扩展,使其能够更好的处理文件上传,扩展的接口名为:org.springframework.web.multipart.MultipartHttpServletRequest

          先用一个类图看一下这个它的底层架构:

          

        下面用代码层面看一下如何实现:

         1、web.xml中配置

          

<bean id="multipartResolver"    
        class="<span style="color:#ff0000;">org.springframework.web.multipart.commons.CommonsMultipartResolver</span>">    
<!--         文件最大值 -->
        <property name="maxUploadSize" value="1048576000" />    
        <property name="defaultEncoding" value="utf-8"/>
<!--         缓存大小 -->
        <property name="maxInMemorySize" value="40960"></property>
</bean>

         2、Controller中实现文件的上传 

@Controller
@RequestMapping("/file")
public class UploadController {
	@RequestMapping(value="/upload")
	public String addUser(@RequestParam("<span style="color:#ff0000;"><strong>file</strong></span>")CommonsMultipartFile file,HttpServletRequest request) throws IOException{
	 
		System.out.println("fileName--->"+file.getOriginalFilename());
		if (!file.isEmpty()) {
			try {
				//定义文件的路径
				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";
	}

              3、jsp中拼出页面

                  注意:两处加红的字体必须一致     

<form name="userForm" action="/ springMVC7/file/upload" method="post" enctype="multipart/form-data">
		选择文件:<input type="text" name="<span style="color:#ff0000;"><strong>file</strong></span>"> 
		
		<input type="submit" value="上传"  οnclick="addUser()">
	</form>


            

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值