java ssm框架实现文件上传
实现:单文件上传、多文件上传(单选和多选),并且用 ajax 异步刷新,在当前界面显示上传的文件
首先springmvc的配置文件要配置上传文件解析器:
1
2
3 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
4 p:defaultEncoding="utf-8">
5
6
7 209715200
8
9
10 4096
11
12
其次在pom.xml中要配置两个上传文件的依赖
1
2
3 commons-io
4 commons-io
5 2.4
6
7
8
9 commons-fileupload
10 commons-fileupload
11 1.3.1
12
13
14
15 org.apache.commons
16 commons-lang3
17 3.3.2
18
单文件上传:
1 /**
2 * 单文件上传
3 * @param file
4 * @param request
5 * @return
6 * @throws IllegalStateException
7 * @throws IOException
8 * @throws JSONException
9 */
10 public static String simUpload(MultipartFile file, HttpServletRequest request)
11 throws IllegalStateException, IOException, JSONException{
12
13 if(!file.isEmpty()){
14 String path = request.getSession().getServletContext().getRealPath("/upload");
15 //定义文件
16 File parent = new File(path);
17 if(!parent.exists()) parent.mkdirs();
18
19 HashMap map = new HashMap();
20
21 String oldName = file.getOriginalFilename();
22
23 long size = file.getSize();
24
25 //使用TmFileUtil文件上传工具获取文件的各种信息
26 //优化文件大小
27 String sizeString = TmFileUtil.countFileSize(size);
28 //获取文件后缀名
29 String ext = TmFileUtil.getExtNoPoint(oldName);
30 //随机重命名,10位时间字符串
31 String newFileName = TmFileUtil.generateFileName(oldName, 10, "yyyyMMddHHmmss");
32
33 String url = "upload/"+newFileName;
34
35 //文件传输,parent文件
36 file.transferTo(new File(parent, newFileName));
37
38 map.put("oldname",oldName);//文件原名称
39 map.put("ext",ext);
40 map.put("size",sizeString);
41 map.put("name",newFileName);//文件新名称
42 map.put("url",url);
43
44 //以json方式输出到页面
45 return JSONUtil.serialize(map);
46 }else{
47 return null;
48 }
49 }
多文件上传(整合了 单选文件和多选文件 的两种)
1 /**
2 * 多文件上传
3 * @param files
4 * @param request
5 * @return
6 * @throws IllegalStateException
7 * @throws IOException
8 * @throws JSONException
9 */
10 public static List> mutlUpload(MultipartFile[] files, HttpServletRequest request)
11 throws IllegalStateException, IOException, JSONException{