文件管理 · 2024年8月22日

java网页下载文件|java程序下载pdf文件

❶ javaweb中的文件下载实现

需要在响复应头部加上一制些标示,告诉浏览器这个是文件下载。如果你用了框架比如struts,需要加如下配置<result name="success" type="stream"><param name="contentType">application/octet-stream;charset=ISO8859-1</param> <param name="inputName">fileStream</param> <param name="contentDisposition">attachment;filename="${fileName}"</param> <param name="bufferSize">2048</param></result>如果没有用框架,就手动在返回对象添加这些contentType

❷ java 如何下载文件

httpURLConnection conn;conn.getInputStream;再将这个stream 写到文件就可以了

❸ java web 大文件上传下载

直接把大文件读取为IO流,之后进行上传下载即可,不用担心文件大,是可以分流下载上传的(setBufferSize(1024))。举例:import hkrt.b2b.view.util.Log;import hkrt.b2b.view.util.ViewUtil;import java.io.ByteArrayOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import org.apache.commons.net.ftp.FTPClient;import org.apache.commons.net.ftp.FTPFile;public class CCFCCBFTP {/*** 上传文件** @param fileName* @param plainFilePath 明文文件路径路径* @param filepath* @return * @throws Exception*/public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {FileInputStream fis = null;ByteArrayOutputStream bos = null;FTPClient ftpClient = new FTPClient();String bl = "false";try {fis = new FileInputStream(plainFilePath);bos = new ByteArrayOutputStream(fis.available());byte[] buffer = new byte[1024];int count = 0;while ((count = fis.read(buffer)) != -1) {bos.write(buffer, 0, count);}bos.flush();Log.info("加密上传文件开始");Log.info("连接远程上传服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSword);FTPFile[] fs;fs = ftpClient.listFiles();for (FTPFile ff : fs) {if (ff.getName().equals(filepath)) {bl="true";ftpClient.changeWorkingDirectory("/"+filepath+"");}}Log.info("检查文件路径是否存在:/"+filepath);if("false".equals(bl)){ViewUtil.dataSEErrorPerformedCommon( "查询文件路径不存在:"+"/"+filepath);return bl;}ftpClient.setBufferSize(1024);ftpClient.setControlEncoding("GBK");// 设置文件类型(二进制)ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);ftpClient.storeFile(fileName, fis);Log.info("上传文件成功:"+fileName+"。文件保存路径:"+"/"+filepath+"/");return bl;} catch (Exception e) {throw e;} finally {if (fis != null) {try {fis.close();} catch (Exception e) {Log.info(e.getLocalizedMessage(), e);}}if (bos != null) {try {bos.close();} catch (Exception e) {Log.info(e.getLocalizedMessage(), e);}}}}/***下载文件** @param localFilePath* @param fileName* @param routeFilepath* @return * @throws Exception*/public static String fileDownloadByFtp(String localFilePath, String fileName,String routeFilepath) throws Exception {FileInputStream fis = null;ByteArrayOutputStream bos = null;FileOutputStream fos = null;FTPClient ftpClient = new FTPClient();String SFP = System.getProperty("file.separator");String bl = "false";try {Log.info("下载并解密文件开始");Log.info("连接远程下载服务器"+CCFCCBUtil.CCFCCBHOSTNAME+":"+22);ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);// ftpClient.connect(CMBCUtil.CMBCHOSTNAME, 2021);// ftpClient.login(CMBCUtil.CMBCLOGINNAME, CMBCUtil.CMBCLOGINPASSWORD);FTPFile[] fs; ftpClient.makeDirectory(routeFilepath);ftpClient.changeWorkingDirectory(routeFilepath);bl = "false";fs = ftpClient.listFiles();for (FTPFile ff : fs) {if (ff.getName().equals(fileName)) {bl = "true";Log.info("下载文件开始。");ftpClient.setBufferSize(1024);// 设置文件类型(二进制)ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);InputStream is = ftpClient.retrieveFileStream(fileName);bos = new ByteArrayOutputStream(is.available());byte[] buffer = new byte[1024];int count = 0;while ((count = is.read(buffer)) != -1) {bos.write(buffer, 0, count);}bos.flush();fos = new FileOutputStream(localFilePath+SFP+fileName);fos.write(bos.toByteArray());Log.info("下载文件结束:"+localFilePath);}}Log.info("检查文件是否存:"+fileName+" "+bl);if("false".equals(bl)){ViewUtil.dataSEErrorPerformedCommon("查询无结果,请稍后再查询。");return bl;}return bl;} catch (Exception e) {throw e;} finally {if (fis != null) {try {fis.close();} catch (Exception e) {Log.info(e.getLocalizedMessage(), e);}}if (bos != null) {try {bos.close();} catch (Exception e) {Log.info(e.getLocalizedMessage(), e);}}if (fos != null) {try {fos.close();} catch (Exception e) {Log.info(e.getLocalizedMessage(), e);}}}}}备注:以上方法就实现了流的二进制上传下载转换,只需要将服务器连接部分调整为本地的实际ftp服务用户名和密码即可。

❹ java程序下载pdf文件

主要是 URL 和 HttpURLConnection 类的运用,看代码:

importjava.io.DataInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.net.HttpURLConnection;importjava.net.URL;publicclassHttpDownloader{_FILE_URL="http://211.103.156.163/u/cms/www/201511/25051940i6ou.pdf";privatestaticfinalStringLOCAL_FILE_PATH="D:/some.pdf";//改成你保存文件的路径publicstaticvoidmain(String[]args){(REMOTE_FILE_URL,LOCAL_FILE_PATH).download();}privateStringremoteFileUrl;privateStringlocalFilePath;publicHttpDownloader(StringremoteFileUrl,StringlocalFilePath){this.remoteFileUrl=remoteFileUrl;this.localFilePath=localFilePath;}publicvoiddownload(){try{URLurl=newURL(remoteFileUrl);=(HttpURLConnection)url.openConnection();httpURLConnection.setConnectTimeout(5*1000);//5000毫秒内没有连接上则放弃连接httpURLConnection.connect();//连接System.out.println("连接URL成功~");intfileLenght=httpURLConnection.getContentLength();System.out.println("文件大小:"+(fileLenght/1024.0)+"KB");System.out.println("开始下载…");try(DataInputStreamdis=newDataInputStream(httpURLConnection.getInputStream());FileOutputStreamfos=newFileOutputStream(localFilePath)){byte[]buf=newbyte[10240];//根据实际情况可以增大buf大小for(intreadSize;(readSize=dis.read(buf))>0;){fos.write(buf,0,readSize);}System.out.println("下载完毕~");}catch(IOExceptionex){System.out.println("下载时出错");}httpURLConnection.disconnect();}catch(IOExceptionex){System.out.println("URL不存在或者连接超时");}}}

❺ java怎么实现下载指定网页中包含的pdf文件。 求代码

解析指定页面,得到pdf文件的地址,用URL来取回pdf的输入流,然后写到本地文件。

❻ 怎样编一个能实现文件下载功能的JAVA程序

java实现文件下载一、采用RequestDispatcher的方式进行1、web.xml文件中增加<mime-mapping> <extension>doc</extension> <mime-type>application/vnd.ms-word</mime-type></mime-mapping>2、程序如下: <%@page language="java" import="java.net.*" pageEncoding="gb2312"%><%response.setContentType("application/x-download");//设置为下载application/x-download String filenamedownload = "/系统解决方案.doc";//即将下载的文件的相对路径 String filenamedisplay = "系统解决方案.doc";//下载文件时显示的文件保存名称 filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8"); response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay); try { RequestDispatcher dispatcher = application.getRequestDispatcher(filenamedownload); if(dispatcher != null) { dispatcher.forward(request,response); } response.flushBuffer(); } catch(Exception e) { e.printStackTrace(); } finally { }%>二、采用文件流输出的方式下载1、web.xml文件中增加<mime-mapping> <extension>doc</extension> <mime-type>application/vnd.ms-word</mime-type></mime-mapping>2、程序如下: <%@page language="java" contentType="application/x-msdownload" import="java.io.*,java.net.*" pageEncoding="gb2312"%><%//关于文件下载时采用文件流输出的方式处理: //加上response.reset(),并且所有的%>后面不要换行,包括最后一个; //因为Application Server在处理编译jsp时对于%>和<%之间的内容一般是原样输出,而且默认是PrintWriter, //而你却要进行流输出:ServletOutputStream,这样做相当于试图在Servlet中使用两种输出机制, //就会发生:getOutputStream() has already been called for this response的错误 //详细请见《More Java Pitfill》一书的第二部分 Web层Item 33:试图在Servlet中使用两种输出机制 270 //而且如果有换行,对于文本文件没有什么问题,但是对于其它格式,比如AutoCAD、Word、Excel等文件 //下载下来的文件中就会多出一些换行符0x0d和0x0a,这样可能导致某些格式的文件无法打开,有些也可以正常打开。 response.reset();//可以加也可以不加 response.setContentType("application/x-download");//设置为下载application/x-download // /../../退WEB-INF/classes两级到应用的根目录下去,注意Tomcat与WebLogic下面这一句得到的路径不同,WebLogic中路径最后没有/ System.out.println(this.getClass().getClassLoader().getResource("/").getPath()); String filenamedownload = this.getClass().getClassLoader().getResource("/").getPath() + "/../../系统解决方案.doc"; String filenamedisplay = "系统解决方案.doc";//系统解决方案.txt filenamedisplay = URLEncoder.encode(filenamedisplay,"UTF-8"); response.addHeader("Content-Disposition","attachment;filename=" + filenamedisplay); OutputStream output = null; FileInputStream fis = null; try { output = response.getOutputStream(); fis = new FileInputStream(filenamedownload); byte[] b = new byte[1024]; int i = 0; while((i = fis.read(b)) > 0) { output.write(b, 0, i); } output.flush(); } catch(Exception e) { System.out.println("Error!"); e.printStackTrace(); } finally { if(fis != null) {

❼ java 在页面点击下载文件,然后关闭该页面,怎么可以让文件继续下载,且后台不报错

使用两个线程,一个线程用于页面显示,第二个线程为文件下载,转为后台线程!当第一个线程关闭后,不会影响到第二个。。