jsp頁面的部分代碼 <form action="insertcp.action" method="post" enctype="multipart/form-data" onsubmit="return yz()"> <table> <tr> <td>產品圖片1:</td> <td><input type="file" name="attach" id="ones" /></td> <td id="divone"></td> </tr> <tr> <td>產品圖片2:</td> <td><input type="file" name="attach" id="two"/></td> <td id="divtwo"></td> </tr> <tr> <td>產品參數圖片:</td> <td><input type="file" name="attach" id="three"/></td> <td id="divthree"></td> </tr> <tr> <td></td> <td><input type="submit" value="上傳" style="width:100px; height:30px; font-weight:bold;"/><input type="reset" value="取消" style="width:100px; height:30px;font-weight:bold;"/></td> <td></td> </tr> </table>
struts.xml 攔截器等配置少不了 <constant name="struts.ui.theme" value="simple"/> <!--解決亂碼 --> <constant name="struts.i18n.encoding" value="UTF-8" /> <!-- 指定容許上傳的文件最大字節數。默認值是2097152(2M)(總) --> <constant name="struts.multipart.maxSize" value="1024102400"/> <package name="default" namespace="/" extends="json-default,struts-default"> <!-- 多個文件上傳 --> <action name="insertcp" class="com.juda.action.AdminGuanliaction" method="insertcp"> <!--圖片存儲路徑--> <param name="savePath">/images</param> <interceptor-ref name="fileUpload"> <!--圖片格式--> <param name="allowedTypes">/image/bmp,image/png,image/gif,image/jpeg,image/jpg,image/x-png, image/pjpeg</param> <!--圖片大小,(單)個。這點容易出錯,讓人忽略,後面有解釋--> <param name="maximumSize">1024102400</param> </interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> <result name="success" type="chain">cpaction</result> <result name="input">MyJsp.jsp</result> </action>
//文件上傳產品信息上傳 private File[] attach; private String[] attachFileName; private String[] attachContentType; private String savePath; public String insertcp() throws Exception{ ServletActionContext.getRequest().setCharacterEncoding("UTF-8"); //獲取數組 File[] file=getAttach(); if(file.length>0 && file!=null){ for(int i=0;i<file.length;i++){ //打印出來路徑 System.out.println(getSavePath()+"\\"+getAttachFileName()[i]); //w文件上傳流 FileOutputStream fos=new FileOutputStream(getSavePath()+"\\"+getAttachFileName()[i]); //創建上傳文件的輸入流 FileInputStream fis=new FileInputStream(file[i]); byte[] by=new byte[1024]; int len=0; while((len=fis.read(by))>0) { fos.write(by,0,len); } fos.close(); fis.close(); } } }