Примеры в этой статье делятся конкретным кодом для загрузки файла реализации Java для вашей ссылки. Конкретный контент заключается в следующем
public httpservletresponse Download (String Path, httpservletresponse ответ) {try {// Путь относится к пути загрузки файла. File file = new File (path); // Получить имя файла. String fileName = file.getName (); // Получить имя суффикса файла. String ext = filename.substring (filename.lastindexof (".") + 1) .touppercase (); // Загрузите файл в форме потока. InputStream fis = new BufferedInputStream (new FileInputStream (path)); byte [] buffer = new Byte [fis.aveable ()]; fis.read (buffer); fis.close (); // четкий ответ ответа ответа.reset (); // Установить ответ заголовка ответа. AddHeader ("Content-Disposition", "Attachment; filename =" + new String (fileName.getBytes ())); response.addheader ("content-juins", "" + file.length ()); OutputStream toclient = new BufferedOutputStream (response.getOutputStream ()); response.setContentType («Приложение/октет-поток»); Toclient.write (буфер); toclient.flush (); toclient.close (); } catch (ioException ex) {ex.printstackTrace (); } return response; } public void downloadlocal (httpservletresponse response) throws filenotfoundexception {// Скачать локальный файл string filename = "operator.doc" .tostring (); // Имя сохранения по умолчанию // чтение inputStream vestream = new FileInputStream ("c: /perator.doc"); // Путь хранилища файла // Установить формат выходного ответа.reset (); response.setContentType ("bin"); response.addheader ("Содержимое-распределение", "Приложение; filename =/" " + filename +"/""); // Цикть данных в потоке байт [] b = новый байт [100]; int len; try {while ((len = instream.read (b))> 0) response.getOutputStream (). write (b, 0, len); instream.close (); } catch (ioException e) {e.printstackTrace (); }} public void downloadnet (httpservletresponse response) Throws malformedurlexception {// Загрузить сетевой файл int bytesum = 0; int byteread = 0; Url url = new URL ("windine.blogdriver.com/logo.gif"); try {urlconnection conn = url.openconnection (); InputStream instriam = conn.getInputStream (); FileOutputStream fs = new FileOutputStream ("c: /abc.gif"); Byte [] buffer = новый байт [1204]; int длина; while ((byteread = instream.read (buffer))! = -1) {bytesum += byteread; System.out.println (Bytesum); fs.write (буфер, 0, Byteread); }} catch (filenotfoundexception e) {e.printstacktrace (); } catch (ioException e) {e.printstackTrace (); }}// способ открыть файлы онлайн
Public void Download (String filePath, httpservletresponse response, boolean isonline) бросает исключение {file f = new File (filePath); if (! f.exists ()) {response.senderror (404, «Файл не найден!»); возвращаться; } BufferedInputStream br = new BufferedInputStream (New FileInputStream (F)); byte [] buf = new Byte [1024]; int len = 0; response.reset (); // Очень важно if (isonline) {// Online Открыть метод URL U = новый URL ("file: ////" + filePath); response.setContentType (u.Openconcenection (). getContentType ()); response.setheader ("Содержимое-распада", "inline; filename =" + f.getName ()); // Имя файла должно быть кодируется как UTF-8} else {// pure метод загрузки response.setContentType ("Application/x-msdownload"); response.setheader ("Distosition", "Attactment; filename =" + f.getName ()); } OutputStream out = response.getOutputStream (); while ((len = br.read (buf))> 0) out.write (buf, 0, len); br.close (); out.close (); }Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.