文件上传及多文件上传

来源:互联网 发布:java开发职业规划 编辑:程序博客网 时间:2024/05/29 03:21

一、单文件上传

注:

1.我这里使用的是springmvc,所以在配置文件中,要添加如下配置(并添加commons-fileupload-1.2.1.jar和commons-io-1.3.2.jar)

2.springmvc其余配置参照之前文章

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><property name="defaultEncoding" value="UTF-8"></property><property name="maxInMemorySize" value="100"></property><property name="uploadTempDir" value="fileresouce/temp"></property><!-- 默认文件夹 --></bean>

表单:

<form action="###" id="sform" method="post" enctype="multipart/form-data"><input type="file" name="myfile" id="myfile"/> <input type="submit" value="上传" ></form>

处理:

public Boolean upload(@RequestParam("myfile") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {String filePath = "";if (!file.isEmpty()) {try {filePath = request.getSession().getServletContext().getRealPath("/") + "/file/" + file.getOriginalFilename();// 文件绝对路径(包括文件名)String filerootpath = request.getSession().getServletContext().getRealPath("/") + "/file/";// 文件夹路径// 如果该文件夹不存在,则手动创建File filerootpathdic = new File(filerootpath);if (!filerootpathdic.exists()) {filerootpathdic.mkdirs();}file.transferTo(new File(filePath));// 上传文件} catch (Exception e) {e.printStackTrace();}}return true;}

#


二、多文件上传

表单:

<form action="${basepath}/fileupload/upload.do" id="sform" method="post" enctype="multipart/form-data"><input type="file" name="myfile" id="myfile" <span style="color:#ff0000;"><strong>multiple="multiple"</strong></span> /> <input type="submit" id="btn" value="上传" ></form>
处理:

public Boolean upload(@RequestParam("myfile") <strong><span style="color:#ff0000;">MultipartFile[] file</span></strong>,HttpServletRequest request,HttpServletResponse response){<span style="color:#ff0000;"><strong>for(MultipartFile f:file){</strong></span>String filePath="";if (!f.isEmpty()) {try {filePath= request.getSession().getServletContext().getRealPath("/")+ "/file/"+ f.getOriginalFilename();String filerootpath = request.getSession().getServletContext().getRealPath("/")+ "/file/";File filerootpathdic = new File(filerootpath);if(!filerootpathdic.exists()){filerootpathdic.mkdirs();}f.transferTo(new File(filePath));} catch (Exception e) {e.printStackTrace();}}}return true; }


注:

1.多文件上传与单文件上传实质是一样的,

区别:1)标签中添加multiple属性;2)后台用数组接收

2.前台表单中name="myfile"的值要与后台@RequestParam("myfile")的参数名称要一致,否则会报400错误

3.我这儿上传文件,不限类型,如有限制,在配置文件中添加相应条件即可



0 0
原创粉丝点击