To begin, I need to develop a servlet which will downlod files.
package com.ics.portlet.JournalManagement;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.ics.portlet.JournalManagement.model.PaperFilesBean;
public class DownloadServlet extends HttpServlet {
private static final long serialVersionUID = 5472703721421222620L;
@SuppressWarnings("unchecked")
public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session = req.getSession();
ArrayList<PaperFilesBean> paperFilesBean = (ArrayList<PaperFilesBean>) session.getAttribute("array_list_of_file");
String fileIdStr = req.getParameter("file_ID");
int fileId = Integer.parseInt(fileIdStr);
PaperFilesBean paperFile = paperFilesBean.get(fileId);
String fileName = paperFile.getFileName();
String _uploadDir = paperFile.getFilepath();
if (!res.isCommitted()) {
if (fileName != null) {
File file = new File(_uploadDir + "/" +fileName);
if (file.isFile()) {
byte[] bytes = new byte[(int) file.length()];
ServletOutputStream out = res.getOutputStream();
res.setContentType("application/pdf");
res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
res.setHeader("Content-Length", String.valueOf(file.length()));
try {
FileInputStream fis = new FileInputStream(file);
fis.read(bytes);
fis.close();
} catch (FileNotFoundException e) {
bytes = "Error.FileNotFound".getBytes();
return;
} catch (IOException e) {
e.printStackTrace();
bytes = "Error.IOException ".getBytes();
return;
}
out.write(bytes);
out.flush();
}
}
}
}
}
Servlet gets the file information from the session. Then I insert the following line to portlet class.
ArrayList<PaperFilesBean> paperFilesBean = PersistenceManager.getPaperFilesBeanById(paperId);
portletSession.setAttribute(ARRAY_LIST_OF_FILE, paperFilesBean, PortletSession.APPLICATION_SCOPE);
Then I define <servlet> and <servlet-mapping> tags in the web.xml file
<servlet>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.ics.portlet.JournalManagement.DownloadServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/download</url-pattern>
</servlet-mapping>
I define jamon file to be the view my portlet and use <a> tag to download file.
<a href="/JournalManagement/download?file_ID=<% fileIndex %>"><% JamonContext.getMean("download_file", languageHashMap) %></a>
finally, I set emptySessionPath="true" in tomcat/conf/server.xml
Please sign in to flag this as inappropriate.