برای دانلود کردن فایل در داخل برنامه از کدهای زیر میتوانید استفاده نمایید. کد در سمت ui به شکل زیر است.
<!-- <af:panelFormLayout maxColumns="2" rows="1"> <af:forEach items="#{viewScope.inboxBean.attachment}" var="attach"> <af:commandImageLink icon="/images/attach.png" text="#{attach.name}" id="cl1"> <af:setActionListener from="#{attach.name}" to="#{viewScope.inboxBean.selectedFile}"/> <af:fileDownloadActionListener filename="#{attach.name}" method="#{viewScope.inboxBean.downloadFile}"/> </af:commandImageLink> <af:spacer height="10" id="s1"/> </af:forEach> </af:panelFormLayout> --><br />
در سمت manged bean که در اینجا downloadFile نام دارد کد زیر قراردارد. در کد زیر فرض شده است که فایلی که کاربر درخواست کرده است یک فایل zip است برای همین از zipfile استفاده شده است در غیر اینصورت به راحتی محتوای فایل خوانده شده و در IU نوشته میگردد.
public void downloadFile(FacesContext facesContext,<br /> OutputStream outputStream) {</p> <p>Row current= JSFUtils.getCurrentRow("myFilesViewIterator");<br /> File zipFile=new File(current.getAttribute("filePath")+"\\"+current.getAttribute("fileName")); //current record...<br /> BeanUtils.logInfo(InboxBean.class.getName(),"downloadFile","going to view file: "+zipFile); //log the code...<br /> ZipInputStream zin=null;<br /> FileInputStream fin=null;<br /> try {</p> <p>fin = new FileInputStream(zipFile);<br /> zin = new ZipInputStream(fin);<br /> ZipEntry entry = null; //read the zip file...<br /> attachment= new ArrayList();<br /> while ((entry = zin.getNextEntry()) != null) {</p> <p>if (entry.getName().endsWith(selectedFile)) {</p> <p>InputStream is= new BufferedInputStream(zin);</p> <p>byte [] buff= new byte[2048];<br /> int len=-1;<br /> while((len=is.read(buff))!=-1){<br /> outputStream.write(buff,0,len); //write file content to the users to see the file<br /> //outputStream.flush();<br /> }</p> <p>}</p> <p>}<br /> BeanUtils.logInfo(InboxBean.class.getName(),"downloadFile","file downloaded successfully in inbox: "+zipFile);<br /> } catch (UnsupportedEncodingException uee) {<br /> // TODO: Add catch code<br /> uee.printStackTrace();<br /> BeanUtils.logError(InboxBean.class.getName(),"downloadFile",uee.getMessage());<br /> } catch (FileNotFoundException fnfe) {<br /> // TODO: Add catch code<br /> fnfe.printStackTrace();<br /> BeanUtils.logError(InboxBean.class.getName(),"downloadFile",fnfe.getMessage());<br /> } catch (IOException ioe) {<br /> // TODO: Add catch code<br /> ioe.printStackTrace();<br /> BeanUtils.logError(InboxBean.class.getName(),"downloadFile",ioe.getMessage());<br /> }finally{</p> <p>if( fin==null){<br /> try{ fin.close();<br /> }catch(Exception e){<br /> System.err.println(e);<br /> }<br /> }<br /> } // Add event code here...<br /> }
نظر خود را وارد کنید: