Display and Download any files from the server file system or from a mapped drive

=== COPY PASTE TO FACES-CONFIG.XML ===

<managed-bean>
    <managed-bean-name>FileShare</managed-bean-name>
    <managed-bean-class>com.acme.FileShare</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
  </managed-bean>

===  COPY PASTE TO A NEW XPAGE OR CUSTOM CONTROL ===

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
	<xp:this.beforeRenderResponse><![CDATA[#{javascript:var fp = requestScope.get("filePath");
if(fp!=null){
	FileShare.download(fp)
	requestScope.remove("filePath")
}}]]></xp:this.beforeRenderResponse>
	
	<xp:repeat id="repeat1" rows="30" var="file">
		<xp:this.value><![CDATA[#{javascript:var f = new java.io.File("c:\\temp");
return FileShare().listFilesForFolder(f);}]]></xp:this.value>
		<xp:panel tagName="div">

			<xp:link escape="true" text="#{javascript:file}"
				id="link1">
				<xp:eventHandler event="onclick" submit="true"
					refreshMode="complete">
					<xp:this.action><![CDATA[#{javascript:requestScope.put("filePath",file)
var fp = requestScope.get("filePath");
if(fp!=null){
	FileShare.download(fp)
}
}]]></xp:this.action>
				</xp:eventHandler>
			</xp:link>
		</xp:panel>

	</xp:repeat></xp:view>



== COPY PASTE TO NEW JAVA CLASS "FileShare"

package com.acme;
import java.io.*;
import java.util.*;
import java.net.URLConnection;
import javax.faces.context.FacesContext;
import com.ibm.xsp.webapp.XspHttpServletResponse;


public class FileShare{
	
	public FileShare(){} 
	
	public static ArrayList listFilesForFolder(final File folder){
		ArrayList<String> files = new ArrayList<String>();
	    for(final File fileEntry : folder.listFiles()){
	       if (fileEntry.isDirectory()){
	            listFilesForFolder(fileEntry);
	       }else{
	    	   files.add(fileEntry.getPath());
	       }
	   }
	    return files;
	}
	
	public static byte[] grabFile(String readFile) throws IOException {

        File file = new File(readFile);
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        InputStream ios = new FileInputStream(file);

        try {
            byte []buffer = new byte[4096];

            int read = 0;
            while ( (read = ios.read(buffer)) != -1 ) {
                ous.write(buffer, 0, read);
            }
        } finally { 
            try {
                 if ( ous != null ) 
                     ous.close();
            } catch ( IOException e) {
            }

            try {
                 if ( ios != null ) 
                      ios.close();
            } catch ( IOException e) {
            }
        }
        return ous.toByteArray();
    }

	public static void download(String filePath) throws IOException {

		String fn = new File(filePath).getName();
		byte[] data = grabFile(filePath);
        XspHttpServletResponse response = (XspHttpServletResponse)FacesContext.getCurrentInstance().getExternalContext().getResponse();
        response.setContentType(URLConnection.guessContentTypeFromName(fn));
        response.setHeader("Content-disposition", "attachment; filename=" + fn);
        OutputStream output = response.getOutputStream();
        output.write(data);
        output.close();
        FacesContext.getCurrentInstance().responseComplete(); 
    }
	
}





This code will display all files from any directory including subfolders from the server in a repeat control, you can click each of the file and download it from the browser, So fo instance, you can point out a common mapped folder on the server and display all files in this folder for download. e.g P:\ACME\

I wish to thank Toby Samples and Panu Haaramo for contributing to this solution.

- You might need to update the java policy file for this to work
- Only tested on Windows



Java
Thomas Adrian
February 13, 2013 2:26 PM
Rating
308

All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.



3 comment(s)Login first to comment...
Steven Rieger
(at 15:44 on 07.10.2015)
OK Last comment. I think there was a permissions error on the folder I was testing. It's sort of working now. I can see it building the list of files / folders but never displays anything.
Also, where do the files download to on the local computer?
Steven Rieger
(at 14:54 on 07.10.2015)
I checked and I have the following in my java.policy: grant { permission java.security.AllPermission; }
So I don't think it's the security issue.
Steven Rieger
(at 14:45 on 07.10.2015)
I was unable to get this to work. I am getting the following error:
10/7/15 1:43 PM: Exception Thrown
Context Path: /dblms/audtrack.nsf
Page Name: /xpFileShare.xsp
Control id: repeat1
Script interpreter error, line=2, col=20: Error calling method 'listFilesForFolder(java.io.File)' on java class 'com.acme.FileShare'
1: var f = new java.io.File("d:\\*.*");
-> 2: return FileShare().listFilesForFolder(f);

Is this due to the java policy? if so do you know what I need to add to the policy file to get it to work?