SpringMVC文件上传的配置实例详解
程序员文章站
2024-03-11 13:33:43
记述一下步骤以备查。
准备工作:
需要把jakarta commons fileupload及jakarta commons io的包放lib里。
我这边...
记述一下步骤以备查。
准备工作:
需要把jakarta commons fileupload及jakarta commons io的包放lib里。
我这边的包是:
commons-fileupload-1.1.1.jar
commons-io-1.3.2.jar
然后在spring-servlet.xml进行multipartresolver配置,不配置好上传会不好用。
<bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver"> <property name="maxuploadsize"><value>100000</value></property> <property name="defaultencoding"><value>utf-8</value></property> </bean>
接下来就是页面了:
注意form的写法和文件上传组件的写法。
<form action="uploadposdetailfile.html" method="post" enctype="multipart/form-data"> <div class="form" > <p> <span class="req"><input id="startdatetxt" name="startdatetxt" class="field size4" title="enter the date" /></span> <label>start date: <span>(date format:mm/dd/yyyy,eg:01/01/2014)</span></label> </p> <p> <span class="req"><input id="enddatetxt" name="enddatetxt" class="field size4" title="enter the date" /></span> <label>end date: <span>(date format:mm/dd/yyyy,eg:12/25/2014)</span></label> </p> <p> <span class="req"><input type="file" name="uploadfilectrl" class="field size4" title="choose the file" /></span> <label>upload file: <span>(click browse to choose)</span></label> </p> </div> <div class="buttons"> <input id="querybtn" type="submit" class="button" value="submit" /> </div> </form>
再在控制器里写处理代码,注意参数和页面控件的对应关系:
@requestmapping(value="/uploadposdetailfile") public string uploadposdetailfile(@requestparam("startdatetxt") string startdatetxt, @requestparam("enddatetxt") string enddatetxt, @requestparam("uploadfilectrl") multipartfile file,httpservletrequest request,httpservletresponse response){ try { system.out.println("@@@@@@@@@1.startdatetxt="+startdatetxt); system.out.println("@@@@@@@@@2.enddatetxt="+enddatetxt); system.out.println("@@@@@@@@@3.file="+file.getoriginalfilename());// 得到上传文件的文件名 if(file.isempty()==false){ inputstream is=file.getinputstream(); inputstreamreader isr = new inputstreamreader(is); bufferedreader br=new bufferedreader(isr); string s; while((s=br.readline())!=null ){ system.out.println(s); } br.close(); isr.close(); is.close(); } return "/pages/posdetail/uploadposdetailresult/index.jsp"; } catch (exception e) { e.printstacktrace(); logger.error(e); request.setattribute("error", e.getclass()); request.setattribute("reason", e.getmessage()); stacktraceelement[] arr=e.getstacktrace(); request.setattribute("stacktraceelements", arr); return "pages/error/index.jsp"; } }