上传下载文件(文件保存在应用服务器)
上传文件:
//利用HtmlInputFile将文件上载到服务器目录<INPUT type="File1" id="myfile" runat="server">
//上传新文件
string path=File1.PostedFile.FileName;//要上传图片在客户机上的绝对路径
string extensionName=System.IO.Path.GetExtension(path);//文件扩展名
string saveName=DateTime.Now.ToString("yyyyMMddhhmmssfff") + extensionName;
//将"当前时间+文件扩展名"做为服务器上文件的文件名,避免文件名重复
string strPath=Server.MapPath("updownload")+"\\"+saveName;
//得到将要保存图片的路径,将图片保存到updownload文件夹
File1.PostedFile.SaveAs(strPath);
下载文件:
//弹出新页面,在新页面中加入以下代码
string filename=Request.QueryString["filename"].ToString();//获取别的页面传递过来的下载文件名
filename=Server.MapPath("updownload")+"\\"+filename; //从updownload文件夹下载文件
//判断下载的文件是否存在
if(!System.IO.File.Exists(filename))
{
Response.Write("<script>alert('文档不存在!');</script>");
return;
};
System.IO.FileInfo file = new System.IO.FileInfo(filename);
Response.ContentType = "application/ms-download";
//下载文件的内容类型,不同的文件格式应指定不同的ContentType
/*
ContentType 属性指定服务器响应的 HTTP 内容类型。如果未指定 ContentType,默认为 text/html。
ContentType 描述内容类型的字符串。该字符串通常被格式化为类型/子类型,其中类型是常规内容范畴而子类为特定内容类型。有关支持内容类型的完整列表,请参阅 Web 浏览器文档或当前的 HTTP 规格说明。
*/
Response.Clear();
Response.Charset = "utf-8"; //设置文件编码
Response.AddHeader("Content-Disposition", "attachment;filename="+System.Web.HttpUtility.UrlEncode(file.Name,System.Text.Encoding.UTF8)); //attachment作为附件下载
Response.AddHeader("Content-Length", file.Length.ToString()); //文件长度
Response.WriteFile(file.FullName);
Response.Flush();
Response.Clear();
Response.End();
--------------------------------------------------------------------
如果要上传大文件,简便的方法是在Web.config或Machine.config中加入
<httpRuntime
executionTimeout="90"
maxRequestLength="4096"
useFullyQualifiedRedirectUrl="false"
minFreeThreads="8"
minLocalRequestFreeThreads="4"
appRequestQueueLimit="100"
/>
maxRequestLength="4096"的单位为k字节

浙公网安备 33010602011771号