2010-09-17 9 views
6

Ho il seguente moduloCome leggere InputStream dal tipo di file HTML in C# ASP.NET senza utilizzare il controllo lato server ASP.NET

<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> 

Quando guardo nella collezione file è vuoto.

HttpFileCollection Files = HttpContext.Current.Request.Files; 

Come si legge il contenuto del file caricato senza utilizzare il controllo laterale del server ASP.NET?

+0

Sono limitato a .Net 2.0 – Deepfreezed

risposta

6

Perché avete bisogno per ottenere il HttpContext currect, basta utilizzare uno della pagina, guardare a questo esempio:

//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))); 
    } 
} 

Il codice di esempio è da Uploading Files in ASP.net without using the FileUpload server control

Btw, non è necessario per utilizzare un controllo pulsante lato server. È possibile aggiungere il codice sopra al caricamento della pagina in cui si controlla se lo stato corrente è un postback.

Buona fortuna!

0

Ecco la mia soluzione finale. Allegare il file ad una email

//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("[email protected]", "name"), new MailAddress("[email protected]", "name")); 
       msg.Subject = "Test"; 
       msg.Body = "Test"; 
       msg.IsBodyHtml = true; 
       msg.Attachments.Add(myAttachment); 

       SmtpClient client = new SmtpClient("smtp"); 
       client.Send(msg); 
      } 
Problemi correlati