在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("attachmentfilename=\"")
.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)
%>
ublic 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", "attachmentfilename=" + 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
}
你有FTPClient就比较好办,假如你的两台FTP服务器分别为fs1和fs2在本地开发代码思路如下:
通过FTPClient连接上fs1,然后下载(可以循环批量下载)到本地服务器,保存到一个临时目录。
下载完成后,FTPClient断开与fs1的连接,记得必须logout。
本地服务器通过FileInputStream将刚下载到临时目录的文件读进来,得到一个List<File>集合。
通过FTPClient连接上fs2,循环List<File>集合,将文件上传至fs2的特定目录,然后清空临时目录,上传完毕后,断开fs2的连接,同样必须logout。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)