在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)
%>
java编程方法下载服务器上的文件到本地客服端,代码如下:
import java.io.BufferedWriterimport java.io.File
import java.io.FileOutputStream
import java.io.FileWriter
import java.io.IOException
import java.io.InputStream
import java.net.URL
import java.net.URLConnection
public class DownLoad {
public static void downloadFile(URL theURL, String filePath) throws IOException {
File dirFile = new File(filePath)
if(!dirFile.exists()){
//文件路径不存在时,自动创建目录
dirFile.mkdir()
}
//从服务器上获取图片并保存
URLConnection connection = theURL.openConnection()
InputStream in = connection.getInputStream()
FileOutputStream os = new FileOutputStream(filePath+"\\123.png")
byte[] buffer = new byte[4 * 1024]
int read
while ((read = in.read(buffer)) > 0) {
os.write(buffer, 0, read)
}
os.close()
in.close()
}
public static void main(String[] args) {
//下面添加服务器的IP地址和端口,以及要下载的文件路径
String urlPath = "http://服务器IP地址:端口/image/123.png"
//下面代码是下载到本地的位置
String filePath = "d:\\excel"
URL url = new URL(urlPath)
try {
downloadFile(url,filePath)
} catch (IOException e) {
e.printStackTrace()
}
}
}
路径就是如:“/user/etc”。
解释:服务器的路径展现形式不是以盘符开始的,而是以“/”开始,之后的路径和windows系统无任何区别,如上面举例的路径,如果想从etc下拿文件,直接“cd /user/etc”之后找到想要的文件,进行下载即可。
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)