A. java response.getOutputStream()實現多個文件下載,已經拿到兩個位元組數組的list,下載的時候如何同時下載
可以一個介面傳多個文李模件,每個文件中間用特定符號拆分,也可以寫一渣擾知個介面前端多次調用,將請求頭的文件格式改為blob,前端獲取文件流後如消調用下載
B. Java文件下載怎麼實現的
下載就很簡單了
把你要下載的文件做成超級鏈接,可以不用任何組件
比如說
下載一個word文檔
<a href="名稱.doc">名稱.doc</a>
路徑你自己寫
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URL;
import java.util.Random;
/**
*
* 實現了下載的功能*/
public class SimpleTh {
public static void main(String[] args){
// TODO Auto-generated method stub
//String path = "http://www.7cd.cn/QingTengPics/倩女幽魂.mp3";//MP3下載的地址
String path ="http://img.99luna.com/music/%CF%EB%C4%E3%BE%CD%D0%B4%D0%C5.mp3";
try {
new SimpleTh().download(path, 3); //對象調用下載的方法
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getFilename(String path){//獲得文件的名字
return path.substring(path.lastIndexOf('/')+1);
}
public void download(String path,int threadsize) throws Exception//下載的方法
{//參數 下載地址,線程數量
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();//獲取HttpURLConnection對象
conn.setRequestMethod("GET");//設置請求格式,這里是GET格式
conn.setReadTimeout(5*1000);//
int filelength = conn.getContentLength();//獲取要下載文件的長度
String filename = getFilename(path);
File saveFile = new File(filename);
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.setLength(filelength);
accessFile.close();
int block = filelength%threadsize ==0?filelength/threadsize:filelength/threadsize+1;
for(int threadid = 0;threadid<=threadsize;threadid++){
new DownloadThread(url,saveFile,block,threadid).start();
}
}
private final class DownloadThread extends Thread{
private URL url;
private File saveFile;
private int block;//每條線程下載的長度
private int threadid;//線程id
public DownloadThread(URL url,File saveFile,int block,int threadid){
this.url = url;
this.saveFile= saveFile;
this.block = block;
this.threadid = threadid;
}
@Override
public void run() {
//計算開始位置的公式:線程id*每條線程下載的數據長度=?
//計算結束位置的公式:(線程id+1)*每條線程下載數據長度-1=?
int startposition = threadid*block;
int endposition = (threadid+1)*block-1;
try {
try {
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.seek(startposition);//設置從什麼位置寫入數據
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5*1000);
conn.setRequestProperty("Range","bytes= "+startposition+"-"+endposition);
InputStream inStream = conn.getInputStream();
byte[]buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer))!=-1){
accessFile.write(buffer, 0, len);
}
inStream.close();
accessFile.close();
System.out.println("線程id:"+threadid+"下載完成");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
C. JAVA 如何一次下載多個文件
創建多線程下載
如果說方便下載,是打包再下載
~~~~~~~~~~~~~~~~~~~~~~
D. 用jsP打包文件列表實現批量下載
你只設置了響應類型,但並沒有返回數據的瀏覽器
E. 高分:用java實現伺服器上多個文件先打包,然後下載,下載完成後刪除包!
可以抄把這些url,name暫存到session裡面
下載和襲上傳可以使用插件jspsmart
很久沒有使用了 稍微看一下API吧jspsmart就是把上傳和下載的工作封裝簡化,所以使用非常簡單的
下載完成後調用file.delete();就在伺服器上刪掉了
F. 怎樣編一個能實現文件下載功能的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)
{
G. java 實現文件批量上傳下載實現方法 以及優勢缺點
給你個不亂的。這個寫的很清楚,基本上你復制源碼就可以。
http://blog.csdn.net/hzc543806053/article/details/7524491
H. JAVA 批量下載.zip
/**
* 報表查詢模塊 ----文件下載流
* @return
* @throws IOException
*/
public InputStream getInputStream() throws IOException {
InputStream ins = new FileInputStream(zipReports());
return ins;
}
/**
* 根據傳過來的報表編號壓縮文件為zip
* @param response
* @param serverPath
* @param str
* @throws IOException
*/
public File zipReports() throws IOException{
List<StatisticalReport> srclist = new ArrayList<StatisticalReport>();
String[] pks = ids.split(",");
if(pks.length > 0){
for(String pk : pks){
String[] str = pk.split("\\|");
StatisticalReport obj = new StatisticalReport();
obj.setCendat(str[0]);
obj.setOrgidt(str[1]);
obj.setRep_code(str[2]);
obj.setCurcde(str[3]);
srclist.add(obj);
}
}
StatisticalReport obj = new StatisticalReport();
obj.setReportList(srclist);
//查詢要下載的報表文件
List<StatisticalReport> list = statisticalReportService.findReportList(obj);
//獲取應用在伺服器上的根目錄
String path = request.getSession().getServletContext().getRealPath(System.getProperty("file.separator"));
List<File> srcList = new ArrayList<File>();
if(list.size() > 0){
for(StatisticalReport statisticalReport : list){
File file = new File(statisticalReport.getFile_path());
if(file.exists()){
srcList.add(file);
}
}
}
Pim_sysUser user = (Pim_sysUser) session.getAttribute(SysConstant.SESSION_USER_DATA);
File zipfile = new File(path + System.getProperty("file.separator") + user.getLogid() + "REPORT.zip");
if(zipfile.exists()){
zipfile.delete();
zipfile.createNewFile();
}
//FileTools.File(, res.getString("help_path"), newFormatFileName);// 上傳文件
ZipUtils.zipFiles(srcList, zipfile);
return zipfile;
}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipUtils {
/**
* 將多個Excel打包成zip文件
*
* @param srcfile
* @param zipfile
*/
public static void zipFiles(List<File> srcfile, File zipfile) {
byte[] buf = new byte[2048];
try {
// Create the ZIP file
// Compress the files
if(srcfile.size() > 0){
// 創建ZipOutputStream類對象
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
for (int i = 0; i < srcfile.size(); i++) {
File file = srcfile.get(i);
FileInputStream in = new FileInputStream(file);
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(file.getName()));// 寫入此目錄的Entry 創建新的進入點
// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(buf)) > 0) {
out.setLevel(9);
out.write(buf, 0, len);
}
// Complete the entry
out.closeEntry();
in.close();
}
out.close();
}else{
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
out.putNextEntry(new ZipEntry(" "));
out.closeEntry();
out.close();
}
// Complete the ZIP file
} catch (IOException e) {
e.printStackTrace();
}
}
}
I. 通過java實現文件下載
在jsp/servlet中斷點/多線程下載文件
<%@ page import="java.io.File" %><%@ page import="java.io.IOException" %><%@ page import="java.io.OutputStream" %><%@ page import="java.io.RandomAccessFile" %><%! public void downloadFile(HttpServletRequest request, HttpServletResponse response, File file) throws IOException { RandomAccessFile raf = new RandomAccessFile(file, "r"); java.io.FileInputStream fis = new java.io.FileInputStream(raf.getFD()); response.setHeader("Server", "www.trydone.com"); response.setHeader("Accept-Ranges", "bytes"); long pos = 0; long len; len = raf.length(); if (request.getHeader("Range") != null) { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); pos = Long.parseLong(request.getHeader("Range") .replaceAll("bytes=", "") .replaceAll("-", "") ); } response.setHeader("Content-Length", Long.toString(len - pos)); if (pos != 0) { response.setHeader("Content-Range", new StringBuffer() .append("bytes ") .append(pos) .append("-") .append(Long.toString(len - 1)) .append("/") .append(len) .toString() ); } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", new StringBuffer() .append("attachment;filename=\"") .append(file.getName()) .append("\"").toString()); raf.seek(pos); byte[] b = new byte[2048]; int i; OutputStream outs = response.getOutputStream(); while ((i = raf.read(b)) != -1) { outs.write(b, 0, i); } raf.close(); fis.close(); }%><% String filePath = request.getParameter("file"); filePath = application.getRealPath(filePath); File file = new File(filePath); downloadFile(request, response, file);%>
是否可以解決您的問題?
J. 用java實現文件的上傳與下載
1.下載簡單,無非是把伺服器上的文件或者資料庫中的BLob(或其他二進制型),用流讀出來,然後寫到客戶端即可,要注意 ContentType。
2.上傳,可以用Apache Commons Upload等開源工具,或者自己寫:
form要用enctype="multipart/form-data"
然後伺服器端也是用IO把客戶端提交的文件流讀入,然後寫到伺服器的文件系統或者資料庫里。不同的資料庫對Lob欄位操作可能有所不同,建議用Hibernate,JPA等成熟的ORM框架,可以不考慮資料庫細節。