Ⅰ 用java实现文件的上传与下载
1.下载简单,无非是把服务器上的文件或者数据库中的BLob(或其他二进制型),用流读出来,然后写到客户端即可,要注意 ContentType。
2.上传,可以用Apache Commons Upload等开源工具,或者自己写:
form要用enctype="multipart/form-data"
然后服务器端也是用IO把客户端提交的文件流读入,然后写到服务器的文件系统或者数据库里。不同的数据库对Lob字段操作可能有所不同,建议用Hibernate,JPA等成熟的ORM框架,可以不考虑数据库细节。
Ⅱ 用java流的方式怎么指定下载到指定目录下
举例代码:
/**
*下载文件。
*@paramurlStr文件的URL
*@paramsavePath保存到的目录
*@paramfileName保存的文件名称
*@paramdescription描述(如:歌曲,专辑封面,歌词等)
*@throwsIOException
*/
publicstaticvoiddownLoad(StringurlStr,StringsavePath,StringfileName,Stringdescription)throwsIOException
{
URLurl=newURL(urlStr);
HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
conn.setConnectTimeout(100000);//设置超时间为10秒
conn.setRequestProperty("User-Agent","Mozilla/4.0(compatible;MSIE5.0;WindowsNT;DigExt)");//防止屏蔽程序抓取而返回403错误
FilesaveDir=newFile(savePath);
Filefile=newFile(saveDir+File.separator+fileName);
try(InputStreaminputStream=conn.getInputStream();
FileOutputStreamfos=newFileOutputStream(file))
{
byte[]flowData=readInputStream(inputStream);
fos.write(flowData);
}catch(Exceptione){
MainFrame.logEvent("字节保存时出现意外:"+e.getMessage());
}
MainFrame.logEvent(description+"下载完成:"+url);
}
MainFrame.logEvent()是我自己弄的日志记录而已,可以忽略不看
Ⅲ “软帝学院”:Java下载文件的几种方式
在Java中,下载文件的方法主要有四种:以流的方式下载、下载本地文件、下载网络文件及支持在线打开的方式。下面分别介绍这几种方法。
1. 以流的方式下载文件,代码如下:
public HttpServletResponse download(String path, HttpServletResponse response) { ... }
2. 下载本地文件,代码如下:
public void downloadLocal(HttpServletResponse response) throws FileNotFoundException { ... }
3. 下载网络文件,代码如下:
public void downloadNet(HttpServletResponse response) throws MalformedURLException { ... }
4. 支持在线打开的方式,代码如下:
public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception { ... }
以上四种方法,能够满足在Java中下载文件的不同需求,可以根据实际情况选择合适的方法进行使用。
Ⅳ java怎么通过链接下载文件,然后保存到指定位置
点击下载,其实就是访问文件路径,通过流读取,然后再指定文件保存位置.还是通过流保存.
file(连接路径)>>input>>out>>file(保存位置)
Ⅳ Java实现文件流下载文件,浏览器无反应,后台无错误!如何解决
//response.reset(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream");//APPLICATION/OCTET-STREAM response.addHeader("Content-Disposition", "attachment; filename=\""+fileName+"\""); //response.setContentLength((int)text.length()); byte[] b=new byte[100]; java.io.OutputStream os=null; java.io.InputStream is=null; try{ is=new java.io.ByteArrayInputStream(text.getBytes()); os=response.getOutputStream(); int len=0; while((len=is.read(b))>0){ os.write(b,0,len); } response.setStatus( response.SC_OK ); //response.flushBuffer(); //os.flush(); //os.close(); is.close(); }catch(IOException e){ //response.reset(); e.printStackTrace(); } fileName的值是一个文件名,如:李四.csv
警告: Parameters: Invalid chunk ignored.
Invalid chunk starting at byte [0] and ending at byte [0] with a value of [null] ignored
问题补充: //response.reset(); response.setCharacterEncoding("UTF-8"); response.setContentType("application/octet-stream");//APPLICATION/OCTET-STREAM response.addHeader("Content-Disposition", "attachment; filename=\""+fileName+"\""); //response.setContentLength((int)text.length()); byte[] b=new byte[100]; java.io.OutputStream os=null; java.io.InputStream is=null; try{ is=new java.io.ByteArrayInputStream(text.getBytes()); os=response.getOutputStream(); int len=0; while((len=is.read(b))>0){ os.write(b,0,len); } response.setStatus( response.SC_OK ); //response.flushBuffer(); //os.flush(); //os.close(); is.close(); }catch(IOException e){ //response.reset(); e.printStackTrace(); } fileName的值是一个文件名,如:李四.csv
警告: Parameters: Invalid chunk ignored.
Invalid chunk starting at byte [0] and ending at byte [0] with a value of [null] ignored 问题补充:大同小异啊,也没有看见关键性的差异。不同的地方我都试过了,还是无法解决!
OpenMind 写道我有一段下载的代码,和你的有几个地方不一样,你自己看着修改一下吧:
File file = new File(savePath + attachment.getPath()); /* 如果文件存在 */ if (file.exists()) { String disName = URLEncoder.encode( attachment.getDisplayName(), "UTF-8"); response.reset(); response.setContentType("application/x-msdownload"); response.addHeader("Content-Disposition", "attachment; filename=\"" + disName + "\""); int fileLength = (int) file.length(); response.setContentLength(fileLength); /* 如果文件长度大于0 */ if (fileLength != 0) { /* 创建输入流 */ InputStream inStream = new FileInputStream(file); byte[] buf = new byte[4096]; /* 创建输出流 */ ServletOutputStream servletOS = response .getOutputStream(); int readLength; while (((readLength = inStream.read(buf)) != -1)) { servletOS.write(buf, 0, readLength); } inStream.close(); servletOS.flush(); servletOS.close(); success = true; } } 问题补充:我已经把Log信息贴出来了,正在找问题,不知道有没有遇到过这个问题的!
lifeidgp 写道1.response.setContentType("application/x-msdownload");加入这样代码试试;
3.用firebug抓包吧。
lifeidgp 写道1.response.setContentType("application/x-msdownload");加入这样代码试试;
3.用firebug抓包吧。
Ⅵ 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){
newHttpDownloader(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不存在或者连接超时");
}
}
}