jquery写下载程序,调用后台方法后没有回应
本帖最后由 zhangxue19857755 于 2012-03-22 14:20:59 编辑 以前写下载都是用asp.net的内置控件,我想用jquery 的ajax()方法调用后台程序,但是确实是调用到后台了,但是下载不了东西为什么啊,高手大神们指教一下,我把代码贴出来:
前台: <form id="form1" runat="server">
<div id="slider" >
</div>
</form>
</body>
</html>
<script type="text/javascript">
//等待DOC元素加载完毕,从后台读取图片并加载到前台页面
$(document).ready(function () {
$.ajax({
type: "post",
url: "../Ws/WebService1.asmx/HelloWorld",
datatype: "html",
async: false,
beforeSend: function (XMLHttpRequest) {
},
success: function (msg) {
$("#slider").append(msg.text)
},
error: function () {
alert('发生错误');
}
});
$('input[type=button]').click(function () {
var ID = $(this).attr("title");
$.ajax({
type: "post",
url: "WebForm6.aspx",
data: 'ID=' + ID,
datatype: "html",
async: true,
beforeSend: function (XMLHttpRequest) {
//如果不是异步读取数据下面则不需要
//$("#showResult").text("请稍后.....");
},
success: function (msg) {
},
error: function () {
alert('发生错误');
}
})
////////////////////////
})
});
</script>
后台的:
public partial class WebForm6 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Request["ID"] != null)
{
string ID = Request["ID"];
string name="";
if (int.Parse(ID) == 1) { name = "truetrue.mp3"; }
if (int.Parse(ID) == 2) { name = "不得不爱.mp3"; }
string filename = "Download/" + name;
if (filename != "")
{
string path = Server.MapPath(filename);
FileInfo file = new FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(name));
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream; charset=gb2312";
Response.Filter.Close();
Response.WriteFile(file.FullName);
Response.End();
}
}
}
}
}
}
请问什么原因, 另外我的表单是在后面拼写的,就是这个HelloWorld()
[WebMethod]
public string HelloWorld()
{
string str = "<table width='90%' style='border:1px solid #ccc'>" +
" <tr> " +
" <td><label>要下载的文件编号:No.</label></td> " +
" <td>文件的名称:</td> " +
" <td>文件的大小:</td> " +
" <td><input type='button' class='download' value='点击下载' title='1' /></td>" +
" </tr> " +
" <tr> " +
" <td><label>要下载的文件编号:No.</label></td> " +
" <td>文件的名称:</td> " +
" <td>文件的大小:</td> " +
" <td><input type='button' class='download' value='点击下载' title='2' /></td>" +
" </tr> " +
" </table> ";
return str;
}
[解决办法]
大概看了你的意思
我是这么做的
前台页面将文件的ID传递到ashx页面来实现下载
参考
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace Asiastar.NR.Ajax
{
/// <summary>
/// $codebehindclassname$ 的摘要说明
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Handler1 : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string id = context.Request["id"].ToString();//获取资源的编号
System.IO.Stream iStream = null;
byte[] buffer = new Byte[10000];
int length;
long dataToRead;
NRBLL.File bf = new Asiastar.NRBLL.File();
Guid guid = new Guid(id);
if (bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"] != null)//判断数据库路径是否存在
{
string filepath = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString();//获取资源完整路径 D:\资源文件\600cc139-14cf-448e-9e50-daa972d35e01.jpg
string Oidfilename = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FileNam"].ToString();//旧文件名称
//string filename = System.IO.Path.GetFileName(filepath);//获取文件名称+后缀名600cc139-14cf-448e-9e50-daa972d35e01.JPG
//int index = filepath.IndexOf(".");
//string filetype = filepath.Substring(index).ToLower();//后缀名
//string newfilename = Oidfilename;
//string filepath1 = bf.FN_SerchPathByFileId(guid).Tables[0].Rows[0]["FilePath"].ToString().Substring(0,filepath.Length - 8);
try
{
string fileName = HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(Oidfilename));//解码(注意这里2层解码)
Oidfilename = Oidfilename.Replace("+", "%20"); //将“+”替换成“空格”
iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
dataToRead = iStream.Length;
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Oidfilename, System.Text.Encoding.UTF8)); //下载的时候下载原来的文件名称
while (dataToRead > 0)
{
if (context.Response.IsClientConnected)
{
length = iStream.Read(buffer, 0, 10000);
context.Response.OutputStream.Write(buffer, 0, length);
context.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
dataToRead = -1;
}
}
}
catch (Exception ex)
{
NR.Error.Log.LogType(ex.ToString());
}
finally
{
if (iStream != null)
{
iStream.Close();
}
}
}
else
{
NR.Error.Log.LogType("找不到文件!");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}