【问题标题】:How to read inputstream from HTML file type in C# ASP.NET without using ASP.NET server side control如何在不使用 ASP.NET 服务器端控件的情况下从 C# ASP.NET 中的 HTML 文件类型读取输入流
【发布时间】:2011-04-13 18:47:21
【问题描述】:

我有以下表格

<form id="upload" method="post" EncType="Multipart/Form-Data" action="reciver.aspx">
        <input type="file" id="upload" name="upload" /><br/>
        <input type="submit" id="save" class="button" value="Save" />            
</form>

当我查看文件集合时,它是空的。

HttpFileCollection Files = HttpContext.Current.Request.Files;

如何在不使用 ASP.NET 服务器端控件的情况下读取上传的文件内容?

【问题讨论】:

  • 我仅限于.Net 2.0

标签: c# asp.net html file-upload


【解决方案1】:

为什么要获取当前的httpcontext,就用页面的那个,看这个例子:

//aspx
<form id="form1" runat="server" enctype="multipart/form-data">
 <input type="file" id="myFile" name="myFile" />
 <asp:Button runat="server" ID="btnUpload" OnClick="btnUploadClick" Text="Upload" />
</form>

//c#
protected void btnUploadClick(object sender, EventArgs e)
{
    HttpPostedFile file = Request.Files["myFile"];
    if (file != null && file.ContentLength )
    {
        string fname = Path.GetFileName(file.FileName);
        file.SaveAs(Server.MapPath(Path.Combine("~/App_Data/", fname)));
    }
}

示例代码来自Uploading Files in ASP.net without using the FileUpload server control

顺便说一句,您不需要使用服务器端按钮控件。您可以将上述代码添加到页面加载中,以检查当前状态是否为回发。

祝你好运!

【讨论】:

    【解决方案2】:

    这是我的最终解决方案。将文件附加到电子邮件中。

    //Get the files submitted form object
                HttpFileCollection Files = HttpContext.Current.Request.Files;
    
                //Get the first file. There could be multiple if muti upload is supported
                string fileName = Files[0].FileName;
    
                //Some validation
                if(Files.Count == 1 && Files[0].ContentLength > 1 && !string.IsNullOrEmpty(fileName))
                { 
                    //Get the input stream and file name and create the email attachment
                    Attachment myAttachment = new Attachment(Files[0].InputStream, fileName);
    
                    //Send email
                    MailMessage msg = new MailMessage(new MailAddress("emailaddress@emailaddress.com", "name"), new MailAddress("emailaddress@emailaddress.com", "name"));
                    msg.Subject = "Test";
                    msg.Body = "Test";
                    msg.IsBodyHtml = true;
                    msg.Attachments.Add(myAttachment);
    
                    SmtpClient client = new SmtpClient("smtp");
                    client.Send(msg);
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-02
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-05-11
      • 2014-02-02
      • 1970-01-01
      相关资源
      最近更新 更多