input file multiple 配合springmvc实现多文件上传

1 篇文章 0 订阅
1 篇文章 0 订阅

1、前端页面的样子

<input id="file" name="file" type="file" multiple="multiple"  />

2、前端的js代码

var formData = new FormData(); 
			var files = $("#file")[0].files;
			for(var i = 0 ; i < files.length ; i ++){
				formData.append('file',files[i]);
			}
3、ajax的代码

$.ajax({
				   url: '${cpath}/biz/xxxx/addFile',
				    type: 'POST',
				    cache: false,
				    data: formData,
				    processData: false,
				    contentType: false
			}).done(function(res) {
				debugger;
			}); 

4、后端的代码

@RequestMapping(value = "addFile", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
	@ResponseBody
	public String addFile(HttpServletRequest request,HttpServletResponse response) {
		
		String rRoles = request.getParameter("rRoles");
		List<MultipartFile> fileList = new ArrayList<>();
		//创建一个通用的多部分解析器 
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		//判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)){
        	//转换成多部分request    
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
            //取得request中的所有文件名  
            fileList = multiRequest.getFiles("file");
            if (fileList == null || fileList.size() <= 0) {
				throw new Exception("上传文件失败");
			}
            System.out.println("");
        }
		return null;
	}
5、xml配置文件配置

    <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- set the max upload size100MB -->  
        <property name="maxUploadSize">  
            <value>104857600</value>  
        </property>  
        <property name="maxInMemorySize">  
            <value>4096</value>  
        </property>  
    </bean> 
6、jar包,除了springmvc常规的jar,还需要commons-fileupload-1.2.2.jar


*注意:关于formdata

The append() method of the FormData interface appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.

The difference between FormData.set and append() is that if the specified key already exists, FormData.set will overwrite all existing values with the new one, whereas append() will append the new value onto the end of the existing set of values.


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值