1.html页面以及js来自于angularjsFileUpload的demo
multiple属性为允许多个文件同时上传
参数设置
url为文件上传路径
formData属性对应的是参数数组,这里以传递id为例
2.springmvc后台
- package com.baosight.webapp.web;
-
- import java.io.File;
- import java.io.IOException;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestBody;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.ResponseBody;
- import org.springframework.web.multipart.MultipartFile;
- import org.springframework.web.multipart.MultipartHttpServletRequest;
- import org.springframework.web.multipart.commons.CommonsMultipartResolver;
-
- import com.baosight.webapp.bean.App;
-
-
-
- @Controller
- @RequestMapping("/ngFileUpload")
- public class NgFileUpload {
-
- @RequestMapping(value="/test", method=RequestMethod.POST )
- @ResponseBody
- public Map<String, Object> ngUpload(HttpServletRequest request,HttpServletResponse res){
- System.out.println("in");
-
- int id= Integer.parseInt(request.getParameter("id"));
- System.out.println("id=="+id);
- Map<String, Object> resMap = new HashMap<String, Object>();
- resMap.put("result", "error");
-
-
- CommonsMultipartResolver multipartResolver =
- new CommonsMultipartResolver(request.getSession().getServletContext());
-
- if(multipartResolver.isMultipart(request)){
-
- MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
- Iterator iter = multiRequest.getFileNames();
- while(iter.hasNext()){
-
- String name=(String)iter.next();
- System.out.println("name:"+name);
-
- MultipartFile file = multiRequest.getFile(name);
- if(file != null){
- String fileName = file.getOriginalFilename();
- String path = "D:/test/" + fileName;
- File localFile = new File(path);
- if(!localFile.getParentFile().exists()) {
-
- localFile.getParentFile().mkdirs();
- System.out.println("parent:"+localFile.getParentFile().getPath());
- }
-
- try {
- file.transferTo(localFile);
- } catch (IOException e) {
-
- e.printStackTrace();
- return resMap;
- }
- }
- }
- }else {
-
- return resMap;
- }
- resMap.put("result", "success");
- return resMap;
- }
-
-
- }
3.备注:
获取参数
request.getParameter("id")
这里的拿到的name为fileItem的alias属性值,相当于form表单中name String name=(String)iter.next();
如果想通过file的name属性值获取文件,对文件进行分类接受,可以通过controller中item的alias属性值。
uploader.uploadAll()是提交所有文件的方法,但是实质上来说该方法是将每个文件提交一次。虽然只触发了一次uploadAll方法,但是有多少个文件就会进多少次后台。实质上是文件进行单个传输。