SpringMVC文件上传的配置实例详解
记述一下步骤以备查。
准备工作:
需要把JakartaCommonsFileUpload及JakartaCommonsio的包放lib里。
我这边的包是:
commons-fileupload-1.1.1.jar
commons-io-1.3.2.jar
然后在spring-servlet.xml进行multipartResolver配置,不配置好上传会不好用。
<beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <propertyname="maxUploadSize"><value>100000</value></property> <propertyname="defaultEncoding"><value>UTF-8</value></property> </bean>
接下来就是页面了:
注意Form的写法和文件上传组件的写法。
<formaction="uploadPosdetailFile.html"method="post"ENCTYPE="multipart/form-data"> <divclass="form"> <p> <spanclass="req"><inputid="startDateTxt"name="startDateTxt"class="fieldsize4"title="Enterthedate"/></span> <label>StartDate:<span>(Dateformat:MM/dd/yyyy,eg:01/01/2014)</span></label> </p> <p> <spanclass="req"><inputid="endDateTxt"name="endDateTxt"class="fieldsize4"title="Enterthedate"/></span> <label>EndDate:<span>(Dateformat:MM/dd/yyyy,eg:12/25/2014)</span></label> </p> <p> <spanclass="req"><inputtype="file"name="uploadFileCtrl"class="fieldsize4"title="Choosethefile"/></span> <label>Uploadfile:<span>(clickbrowsetochoose)</span></label> </p> </div> <divclass="buttons"> <inputid="queryBtn"type="Submit"class="button"value="Submit"/> </div> </form>
再在控制器里写处理代码,注意参数和页面控件的对应关系:
@RequestMapping(value="/uploadPosdetailFile") publicStringuploadPosdetailFile(@RequestParam("startDateTxt")StringstartDateTxt, @RequestParam("endDateTxt")StringendDateTxt, @RequestParam("uploadFileCtrl")MultipartFilefile,HttpServletRequestrequest,HttpServletResponseresponse){ try{ System.out.println("@@@@@@@@@1.startDateTxt="+startDateTxt); System.out.println("@@@@@@@@@2.endDateTxt="+endDateTxt); System.out.println("@@@@@@@@@3.file="+file.getOriginalFilename());//得到上传文件的文件名 if(file.isEmpty()==false){ InputStreamis=file.getInputStream(); InputStreamReaderisr=newInputStreamReader(is); BufferedReaderbr=newBufferedReader(isr); Strings; while((s=br.readLine())!=null){ System.out.println(s); } br.close(); isr.close(); is.close(); } return"/pages/posdetail/uploadposdetailresult/index.jsp"; }catch(Exceptione){ 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"; } }