在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()
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)