素材巴巴 > 程序开发 >

angularjsFileUpload Springmvc上传文件

程序开发 2023-09-03 17:22:48

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	)@ResponseBodypublic Map ngUpload(HttpServletRequest request,HttpServletResponse res){System.out.println("in");//接收参数int id= Integer.parseInt(request.getParameter("id"));System.out.println("id=="+id);Map resMap = new HashMap();resMap.put("result", "error");//解析器解析request的上下文CommonsMultipartResolver multipartResolver =new CommonsMultipartResolver(request.getSession().getServletContext());//先判断request中是否包涵multipart类型的数据,if(multipartResolver.isMultipart(request)){//再将request中的数据转化成multipart类型的数据MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;Iterator iter = multiRequest.getFileNames();while(iter.hasNext()){//这里的name为fileItem的alias属性值,相当于form表单中nameString name=(String)iter.next();System.out.println("name:"+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) {// TODO Auto-generated catch blocke.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方法,但是有多少个文件就会进多少次后台。实质上是文件进行单个传输。


标签:

素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。