使用FileUpload上传:
- protected void btnUpload_Click(object sender, EventArgs e)
- {
- if (FileUpload1.HasFile)
- {
- /*通过文件扩展名判断文件类型*/
- string fileExt = System.IO.Path.GetExtension(FileUpload1.FileName);
- if (fileExt != ".doc" && fileExt != ".docx" && fileExt != ".wps")
- {
- lblMsg.Text = "文件类型错误!应为:doc、docx或wps";
- return;
- }
- /*限制文件大小*/
- if (FileUpload1.PostedFile.ContentLength > 100 * 1024)
- {
- lblMsg.Text = "文件应小于100KB";
- return;
- }
- FileUpload1.SaveAs(Server.MapPath("虚拟路径") + FileUpload1.FileName);
- lblMsg.Text = "文件上传成功!";
- }
- else
- {
- lblMsg.Text = "未选择上传文件";
- }
- }
文件下载:
- protected void btnDownload_Click(object sender, EventArgs e)
- {
- string fileName = "文件名.扩展名";
- FileInfo fileInfo = new FileInfo(Server.MapPath("虚拟路径") + fileName);
- Response.ContentType = "application/octet-stream";
- Response.AddHeader("Content-Disposition", "p_w_upload;FileName=" + HttpUtility.UrlEncode(fileName));
- /*这里注意,如果没有下面一句,很可能会造成“文件已损坏”等情况*/
- Response.AddHeader("Content-Length", fileInfo.Length.ToString());
- Response.WriteFile(Server.MapPath("虚拟路径") + fileName);
- }