Struts - скачать файл с примера сайта
Чтобы пользователь мог загрузить файл из вашего веб-проекта Struts, вы должны сообщить «HttpServletResponse», чтобы он возвращал файл приложения вместо обычной HTML-страницы.
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=downloadfilename.csv");
На стороне сервера вы можете скачать файл тремя разными способами.
1. Файловая система
Получить его из файловой системы
FileInputStream in =
new FileInputStream(new File("C:\\filename.zip"));
2. Веб-путь проекта
Предположим, ваш файл расположен в «http://yourname.com/StrutsExample/upload/filename.zip», а «StrutsExample» - это имя вашего проекта (контекст serlvet).
//jndi:/yourname.com/StrutsExample/upload/filename.zip
URL url = getServlet().getServletContext().getResource("upload/filename.zip");
InputStream in = url.openStream();
3. Байтовый массив
Если вы извлекаете файлы или данные BLOB-объектов из базы данных, они обычно возвращаются в виде байтового массива.
byte[] bytes = new byte[4096]; InputStream in = new ByteArrayInputStream(bytes);
Загрузите этот пример файла загрузки Struts -Struts-Download-File-Example.zip
1. Класс действий
Класс действия для возврата файла приложения вместо обычной HTML-страницы и получения файла «superfish.zip» для загрузки пользователем.
package com.example.common.action;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class DownloadFileAction extends Action{
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//return an application file instead of html page
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=superfish.zip");
try
{
//Get it from file system
FileInputStream in =
new FileInputStream(new File("C:\\superfish.zip"));
//Get it from web path
//jndi:/localhost/StrutsExample/upload/superfish.zip
//URL url = getServlet().getServletContext()
// .getResource("upload/superfish.zip");
//InputStream in = url.openStream();
//Get it from bytes array
//byte[] bytes = new byte[4096];
//InputStream in = new ByteArrayInputStream(bytes);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[4096];
//copy binary content to output stream
while(in.read(outputByte, 0, 4096) != -1){
out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
2. Страница JSP
Download file from server -
3. struts-config.xml
Файл конфигурации Struts.
