[英]Download files from file server using javascript and C#
我在文件服務器中有一個文件(例如:本地目錄E:\\ drive)
我有一種服務器端方法來下載文件
[System.Web.Services.WebMethod]
public static void DownloadFile(string AcctNum, string OfficeCode)
{
string fName = "E:\\FILES\\STATEMENTS\\sample.pdf";
FileInfo fi = new FileInfo(fName);
long sz = fi.Length;
HttpContext.Current.Response.ClearContent();
if (System.IO.Path.GetFileName(fName).EndsWith(".txt"))
{
HttpContext.Current.Response.ContentType = "application/txt";
}
else if (System.IO.Path.GetFileName(fName).EndsWith(".pdf"))
{
HttpContext.Current.Response.ContentType = "application/pdf";
}
else
{
HttpContext.Current.Response.ContentType = "image/jpg";
}
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}", System.IO.Path.GetFileName(fName)));
HttpContext.Current.Response.AddHeader("Content-Length", sz.ToString());
HttpContext.Current.Response.TransmitFile(fName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
我正在從javascript函數調用此方法,如下所示
function DownloadStatement(account,office) {
PageMethods.DownloadFile(account,office);
}
DownloadFile()正在執行,但文件未通過瀏覽器下載。
我在這里想念什么。 請幫忙。
試試this.put這在您的代碼下載
string filePath = Server.MapPath("your filepath");
FileInfo file = new FileInfo(filePath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = GetMimeType(file.Name);
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
並將此方法添加到您的代碼中以獲取文件類型。 因此您不需要檢查文件類型
private string GetMimeType(string fileName)
{
string mimeType = "application/unknown";
string ext = System.IO.Path.GetExtension(fileName).ToLower();
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(ext);
if (regKey != null && regKey.GetValue("Content Type") != null)
{
mimeType = regKey.GetValue("Content Type").ToString();
}
return mimeType;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.