Ⅰ 用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不存在或者連接超時");
}
}
}