有很多用户想要上传一些文件和希望服务器下载文件。 ASP.net提供FileUpload控件上传文件到Web服务器。它提供了简单的方法来上传文件到服务器,该编码器还没有写全逻辑读取和写入文件到Web服务器。
在这里,我会提到如何使用文件上传控件把文件上传到服务器。添加一个按钮,从服务器下载文件。响应对象提供AddHeader方法,您可以提到的页眉不同类型传递给客户端。在这里,我使用的内容和附件配置属性,在这里您可以指定文件名传递给客户端。对于客户端Web浏览器将提示用户下载该文件。
Client Side Code: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="1" cellspacing="0" cellpadding="0" id="tbl">
<tbody>
<tr>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" BorderStyle="Solid" ForeColor="Black"
Width="329px" BackColor="White" />
</td>
</tr>
</tbody>
</table>
<table border="1" cellspacing="0" cellpadding="0" id="tblButton">
<tbody>
<tr>
<td>
<asp:Button ID="btnUpload" Text="Upload" runat="server" OnClick="btnUpload_Click" />
</td>
<td>
<asp:Button ID="btnDownload" Text="Download" runat="server" OnClick="btnDownload_Click" />
</td>
</tr>
</tbody>
</table>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnUpload_Click(object sender, EventArgs e)
{
String filePath = FileUpload1.FileName;
String strFileName = "";
if (FileUpload1.PostedFile != null)
{
HttpPostedFile file = FileUpload1.PostedFile;
//Get the size of the file so you can read the file
int contentLen = file.ContentLength;
if (contentLen > 0)
{
strFileName = Path.GetFileName(filePath);
file.SaveAs(Server.MapPath(strFileName));
}
}
}
protected void btnDownload_Click(object sender, EventArgs e)
{
string fileName = "Amazon.txt";
string filePath = Server.MapPath(fileName);
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=" + filePath);
Response.ContentType = "application/octet-stream";
Response.WriteFile(filePath);
Response.Flush();
Response.End();
}
}
希望这将指导你如何上传和下载网络服务器上的文件。