我正在尝试在asp.net 2.0中创建一个 Web 服务来下载文件(打开或保存文件的弹出窗口),以这种方式:
$.ajax({
type: "POST",
url: "webservice.asmx/download",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (res) {
console.log("donwloaded");
}
});
在“webservice.asmx”中
[WebMethod()]
public byte[] DownloadFile(string FName)
{
System.IO.FileStream fs1 = null;
fs1 = System.IO.File.Open(FName, FileMode.Open, FileAccess.Read);
byte[] b1 = new byte[fs1.Length];
fs1.Read(b1, 0, (int)fs1.Length);
fs1.Close();
return b1;
}
[WebMethod]
public void download()
{
string filename = "test.txt";
string path = "C:\\test.txt";
byte[] ls1 = DownloadFile(path);
HttpResponse response = Context.Response;
response.Clear();
response.BufferOutput = true;
response.ContentType = "application/octet-stream";
response.ContentEncoding = Encoding.UTF8;
response.AppendHeader("content-disposition", "attachment; filename=" + filename);
response.BinaryWrite(ls1);
response.Flush();
response.Close();
}
通过这种方式,我看到了文件的内容(我无法通过弹出窗口下载文件)。
我哪里错了?是否有可能做到这一点?
提前致谢