前言:下载更多资源,查看更多技术教程,可移步至www.hjiacake.com,涵盖了所有的常用技术,软考等
情景:客户端对服务器中的文件进行下载(C#环境)
分析:服务器中的文件下载,如果需要用到cs类进行下载,则需要将下载对象返回至前端页面,这能正确下载,否则客户端将无法进行下载。
错误例子:
页面:
$.ajax({
async: false,
url: '/handler/statistical/Task.ashx?view=downLoadFile',
data: { formPams: '{"url":' + '"'+url + '"'+',"fileName":' + '"'+fileName +'"'+ '}' },
dataType: "json",
success: function (datas) {
//逻辑判断
}
});
cs:
if (view == "downLoadFile1")
{
string url = "", fileName = "";
if (jsonForm != "")
{
JObject o = (JObject)JsonConvert.DeserializeObject(jsonForm);
//服务器路径
url = o["url"].ToString();
//文件名称,不包含后缀
fileName = o["fileName"].ToString();
}
//要使用HttpContext需要在调用接口时使用http
//url = HttpContext.Current.Request.Form["url"].ToString();
url = "http://47.104.242.35:90/WordFile" + url;
//在线打开
//Process.Start(url.ToString());
//fileName = HttpContext.Current.Request.Form["fileName"].ToString();
//string FileUlr = HttpContext.Current.Server.MapPath("~");//获取文件所在目录,本地启动可以使用这个路径
string FileUlr = "D://FB_OP/";
//本地路径(包含名称)
string path = FileUlr + fileName + ".doc";
//string tempPath = Path.GetDirectoryName(FileUlr) + @"temp";
string tempPath = FileUlr + @"temp";
Directory.CreateDirectory(tempPath); //创建临时文件目录
string tempFile = tempPath + @"" + Path.GetFileName(path); //临时文件
if (File.Exists(tempFile))
{
File.Delete(tempFile); //存在则删除
}
try
{
FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream();
//创建本地文件写入流
//Stream stream = new FileStream(tempFile, FileMode.Create);
byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, (int)bArr.Length);
while (size > 0)
{
//stream.Write(bArr, 0, size);
fs.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, (int)bArr.Length);
}
fs.Close();
responseStream.Close();
Process.Start(tempFile.ToString());
//模仿返回格式
jsonText = "1";
}
catch (Exception ex)
{
HttpContext.Current.Response.Write("<script langauge=javascript>alert(‘文件下载失败!’);</script>");
HttpContext.Current.Response.End();
throw ex;
}
}
正确例子:
页面:
var PARAMS = {"url":url,"fileName":fileName};
var temp = document.createElement("form");
temp.action = "/handler/statistical/Task.ashx?view=downLoadFile";
temp.method = "post";
temp.style.display = "none";
for (var x in PARAMS) {
var opt = document.createElement("textarea");
opt.name = x;
opt.value = PARAMS[x];
temp.appendChild(opt);
}
document.body.appendChild(temp);
temp.submit();
return temp;
cs:
if (view == "downLoadFile")
{
string url = "", fileName = "";
url = HttpContext.Current.Request.Form["url"].ToString();
fileName = HttpContext.Current.Request.Form["fileName"].ToString();
string FileUlr = System.Web.HttpContext.Current.Server.MapPath("~");//获取文件所在目录
FileUlr =FileUlr+ "..\wcf\WordFile" + url;
//FileUlr = FileUlr + "aaa.txt";
string OutFileName = fileName;
if (File.Exists(FileUlr))//判断该文件是否存在
{
FileInfo fi = new FileInfo(FileUlr);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
string tempfile = Path.GetFileName(FileUlr);//获取文件名称
tempfile = OutFileName + tempfile.Substring(tempfile.LastIndexOf("."));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = false;
// 这一步调试时中文文件名也是正常。
string DownloadFileName = null;
string browser = HttpContext.Current.Request.UserAgent.ToUpper();
if (browser.Contains("MS") == true && browser.Contains("IE") == true)//判断当前用户使用的浏览器类型
{
DownloadFileName = HttpUtility.UrlEncode(tempfile); // 这一步调试时中文文件名也是正常。在ie中中文显示正常,但在firefox中,中文依然为
//乱码,所以这里要判断用户使用浏览器类型,来保持中文文件名的正常显示
}
else if (browser.Contains("FIREFOX") == true)
{
DownloadFileName = """ + tempfile + """;
}
else
{
DownloadFileName = HttpUtility.UrlEncode(tempfile);// 这一步弹出下载保存的对话框,出现文件名乱码,但变量中的文件名是正常的。
}
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + DownloadFileName);//为用户保存文件是显示的名称
HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.WriteFile(FileUlr);//用response来返回文件的路径
HttpContext.Current.Response.Flush();//清空response
HttpContext.Current.Response.End();
}
else
{
HttpContext.Current.Response.Write("<script langauge=javascript>alert(‘文件不存在!’);</script>");
HttpContext.Current.Response.End();
}
PS:下载更多资源,查看更多技术教程,可移步至www.hjiacake.com,涵盖了所有的常用技术,软考等
最后
以上就是痴情香水最近收集整理的关于C# 代码客户端下载服务器文件的全部内容,更多相关C#内容请搜索靠谱客的其他文章。
发表评论 取消回复