Автор оригинала: mkyong.
Вот как простой пример java демонстрирует, как разрешить пользователю загружать файл с веб-сайта. Независимо от того, используете ли вы struts, JSP, Spring или любую другую платформу java, логика одна и та же.
1) Сначала мы должны установить HttpServletResponse ответ , чтобы сообщить браузеру о том, что система собирается вернуть файл приложения вместо обычная html-страница
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=downloadfilename.csv");
мы также можем указать имя загружаемого файла в вложение; имя файла= ,
2) Есть 2 способа разрешить пользователю загружать файл с веб-сайта
Чтение файла из физического местоположения
File file = new File("C:\\temp\\downloadfilename.csv");
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
fileIn.close();
out.flush();
out.close();
Экспортируйте данные базы данных или строку непосредственно во входной поток для загрузки пользователем.
StringBuffer sb = new StringBuffer("whatever string you like");
InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(in.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();
3) Сделано
Вот как мой пример struts демонстрирует, как напрямую записывать данные во входной поток и выводить их как “temp.cvs”, чтобы позволить пользователю загружать.
public ActionForward export(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//tell browser program going to return an application file
//instead of html page
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename=temp.csv");
try
{
ServletOutputStream out = response.getOutputStream();
StringBuffer sb = generateCsvFileBuffer();
InputStream in =
new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(in.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
in.close();
out.flush();
out.close();
}
return null;
}
private static StringBuffer generateCsvFileBuffer()
{
StringBuffer writer = new StringBuffer();
writer.append("DisplayName");
writer.append(',');
writer.append("Age");
writer.append(',');
writer.append("HandPhone");
writer.append('\n');
writer.append("mkyong");
writer.append(',');
writer.append("26");
writer.append(',');
writer.append("0123456789");
writer.append('\n');
return writer;
}
Вот пример загрузки файла в коде сервлета
Оригинал: “https://mkyong.com/java/how-to-download-file-from-website-java-jsp/”