Как скачать файл с сайта - Java / Jsp
Здесь я показываю простой пример Java, чтобы продемонстрировать, как разрешить пользователю загружать файл с веб-сайта. Независимо от того, используете ли вы struts, JSP, Spring или любую другую платформу Java, логика остается той же.
1) Сначала мы должны установитьHttpServletResponse response, чтобы сообщить браузеру о том, что система будет возвращать файл приложения вместо обычной html-страницы.
response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=downloadfilename.csv");
мы также можем указать имя файла загрузки вattachment;filename=, в приведенном выше примере экспортировать имя файла csv «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();
Экспортируйте данные базы данных или строку непосредственно в InputStream для загрузки пользователем.
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, чтобы продемонстрировать, как напрямую записывать данные в InputStream и выводить их как «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("example"); writer.append(','); writer.append("26"); writer.append(','); writer.append("0123456789"); writer.append('\n'); return writer; }