SpringMVC文件上傳的設置裝備擺設實例詳解。本站提示廣大學習愛好者:(SpringMVC文件上傳的設置裝備擺設實例詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是SpringMVC文件上傳的設置裝備擺設實例詳解正文
記敘一下步調以備查。
預備任務:
須要把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"; } }