目标:实现点击链接弹出文件下载对话框。
代码:
<html><head>代码下载</head>
<title>代码下载</title>
<body>
<a href="Web.rar" >download</a>
</body>
</html
浏览器支持能够打开的格式,他都会默认直接在线打开(比如word或图片),不支持的格式,他就会弹出下载提示。最好是做成.rar格式的文件。
不知道你的do_download.jsp怎么写的。我给你写个吧<%
response.setContentType("application/x-download")//设置为下载application/x-download
String
filedownload
=
"下载的文件的相对路径"
String
filedisplay
=
"下载文件时显示的文件保存名称"
filedisplay
=
URLEncoder.encode(filedisplay,"UTF-8")
response.addHeader("Content-Disposition","attachmentfilename="
+
filedisplay)
try
{
RequestDispatcher
dis
=
request
.getRequestDispatcher(filedownload)
if(dis!=
null)
{
dis.forward(request,response)
}
response.flushBuffer()
}
catch(Exception
e)
{
e.printStackTrace()
}
finally
{
}
%>
这样应该可以下载了吧,注意,一定要注意我写的汉字,引号里面就是要自己加需要别人下载的文件
#region 下载文件/**//// <summary>
/// 从FTP服务器下载文件,使用与远程文件同名的文件名来保存文件
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
/// <param name="LocalPath">本地路径</param>
public bool DownloadFile(string RemoteFileName, string LocalPath)
{
return DownloadFile(RemoteFileName, LocalPath, RemoteFileName)
}
/**//// <summary>
/// 从FTP服务器下载文件,指定本地路径和本地文件名
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
/// <param name="LocalPath">本地路径</param>
/// <param name="LocalFilePath">保存文件的本地路径,后面带有"\"</param>
/// <param name="LocalFileName">保存本地的文件名</param>
public bool DownloadFile(string RemoteFileName, string LocalPath, string LocalFileName)
{
byte[] bt = null
try
{
if (!IsValidFileChars(RemoteFileName) || !IsValidFileChars(LocalFileName) || !IsValidPathChars(LocalPath))
{
throw new Exception("非法文件名或目录名!")
}
if (!Directory.Exists(LocalPath))
{
throw new Exception("本地文件路径不存在!")
}
string LocalFullPath = Path.Combine(LocalPath, LocalFileName)
if (File.Exists(LocalFullPath))
{
throw new Exception("当前路径下已经存在同名文件!")
}
bt = DownloadFile(RemoteFileName)
if (bt != null)
{
FileStream stream = new FileStream(LocalFullPath, FileMode.Create)
stream.Write(bt, 0, bt.Length)
stream.Flush()
stream.Close()
return true
}
else
{
return false
}
}
catch (Exception ep)
{
ErrorMsg = ep.ToString()
throw ep
}
}
/**//// <summary>
/// 从FTP服务器下载文件,返回文件二进制数据
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
public byte[] DownloadFile(string RemoteFileName)
{
try
{
if (!IsValidFileChars(RemoteFileName))
{
throw new Exception("非法文件名或目录名!")
}
Response = Open(new Uri(this.Uri.ToString() + RemoteFileName), WebRequestMethods.Ftp.DownloadFile)
Stream Reader = Response.GetResponseStream()
MemoryStream mem = new MemoryStream(1024 * 500)
byte[] buffer = new byte[1024]
int bytesRead = 0
int TotalByteRead = 0
while (true)
{
bytesRead = Reader.Read(buffer, 0, buffer.Length)
TotalByteRead += bytesRead
if (bytesRead == 0)
break
mem.Write(buffer, 0, bytesRead)
}
if (mem.Length >0)
{
return mem.ToArray()
}
else
{
return null
}
}
catch (Exception ep)
{
ErrorMsg = ep.ToString()
throw ep
}
}
#endregion