java實現文件下載
㈠ java 下載文件的方法怎麼寫
參考下面
public HttpServletResponse download(String path, HttpServletResponse response) {
try {
// path是指欲下載的文件的路徑。
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.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 設置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}
// 下載本地文件
public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {
String fileName = "Operator.doc".toString(); // 文件的默認保存名
// 讀到流中
InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路徑
// 設置輸出的格式
response.reset();
response.setContentType("bin");
response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// 循環取出流中的數據
byte[] b = new byte[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 inStream = conn.getInputStream();
FileOutputStream fs = new FileOutputStream("c:/abc.gif");
byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//支持在線打開文件的一種方式
public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0;
response.reset(); // 非常重要
if (isOnLine) { // 在線打開方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
// 文件名應該編碼成UTF-8
} else { // 純下載方式
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
㈡ java response.getOutputStream()實現多個文件下載,已經拿到兩個位元組數組的list,下載的時候如何同時下載
可以一個介面傳多個文件,每個文件中間用特定符號拆分,也可以寫一個介面前端多次調用,將請求頭的文件格式改為blob,前端獲取文件流後調用下載
㈢ 怎樣編一個能實現文件下載功能的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實現文件的下載,如何提高下載速度(非web開發)
下面貼出的代碼是一個簡單的讀取遠程文件保存到本地的實現,至於提高下載速度你可以利用多線程,具體可參考最下面的那個網址——
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class DownloadTester {
 public static void main(String[] args) throws IOException {
  String urlStr = "https://gss0.bdstatic.com/70cFsjip0QIZ8tyhnq/img/logo-.gif";
  String path = "D:/";
  
  String name = urlStr.substring(urlStr.trim().lastIndexOf("/"));
  
  URL url = new URL(urlStr);
  InputStream in = url.openConnection().getInputStream();
  
  File file = new File(path + name);
  FileOutputStream out = new FileOutputStream(file, true);
  
  int counter = 0;
  int ch;
  byte[] buffer = new byte[1024];
  while ((ch = in.read(buffer)) != -1) {
   out.write(buffer, 0, ch);
   counter += ch;
   System.out.println(counter + ":byte");
  }
  out.flush();
  in.close();
  out.close();
 }
}
㈤ 如何利用位元組流實現java的文件上傳下載
實現上傳下載實際上就是io的轉換。舉例:
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實現文件的上傳與下載
1.下載簡單,無非是把伺服器上的文件或者資料庫中的BLob(或其他二進制型),用流讀出來,然後寫到客戶端即可,要注意 ContentType。
2.上傳,可以用Apache Commons Upload等開源工具,或者自己寫:
form要用enctype="multipart/form-data"
然後伺服器端也是用IO把客戶端提交的文件流讀入,然後寫到伺服器的文件系統或者資料庫里。不同的資料庫對Lob欄位操作可能有所不同,建議用Hibernate,JPA等成熟的ORM框架,可以不考慮資料庫細節。
