Click here to Skip to main content
15,896,727 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,


UploadCS.ascx File Code:

C#
<%@ WebHandler Language="C#" Class="UploadCS" %>
using System;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Collections.Generic;
public class UploadCS : IHttpHandler, IRequiresSessionState {
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "text/plain";
        context.Response.Expires = -1;
        try
        {
            List<httppostedfile> files = (List<httppostedfile>)context.Session["Files"];
            HttpPostedFile postedFile = context.Request.Files["Filedata"];
            files.Add(postedFile);
            string filename = postedFile.FileName;
            context.Response.Write(filename);
            context.Response.StatusCode = 200;
        }
        catch (Exception ex)
        {
            context.Response.Write("Error: " + ex.Message);
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

.CS File Code

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Configuration;
using System.Net.Mail;
using System.IO;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["Files"] = new List<httppostedfile>();
        }
    }

    protected void btnSend_Click(object sender, EventArgs e)
    {
        using (MailMessage mailMessage = new MailMessage())
        {
            mailMessage.From = new MailAddress("user@gmail.com");
            mailMessage.Subject = txtSubject.Text.Trim();
            mailMessage.Body = txtBody.Text.Trim();
            mailMessage.IsBodyHtml = true;
            mailMessage.To.Add(new MailAddress(txtTo.Text.Trim()));
            List<httppostedfile> files = (List<httppostedfile>)Session["Files"];
            foreach (HttpPostedFile file in files)
            {
                mailMessage.Attachments.Add(new Attachment(file.InputStream, Path.GetFileName(file.FileName), file.ContentType));
            }

            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.EnableSsl = true;
            System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
            NetworkCred.UserName = mailMessage.From.Address;
            NetworkCred.Password = "<password>";
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = NetworkCred;
            smtp.Port = 587;
            smtp.Send(mailMessage);
        }
        Response.Redirect(Request.Url.AbsoluteUri);
    }

    [WebMethod]
    public static void RemoveFile(string fileName)
    {
        List<httppostedfile> files = (List<httppostedfile>)HttpContext.Current.Session["Files"];
        files.RemoveAll(f => f.FileName.ToLower().EndsWith(fileName.ToLower()));
    }
}


.aspx File code

XML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.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>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
        input[type=text]{width:250px}
        textarea{width:250px;height:150px}
    </style>
    <link rel="Stylesheet" type="text/css" href="CSS/uploadify.css" />
    <script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="scripts/jquery.uploadify.js"></script>
    <script type="text/javascript">
        $(function () {
            $("[id*=FileUpload1]").fileUpload({
                'uploader': 'scripts/uploader.swf',
                'cancelImg': 'images/cancel.png',
                'buttonText': 'Attach Files',
                'script': 'UploadCS.ashx',
                'folder': 'uploads',
                'multi': true,
                'auto': true,
                'onSelect': function (event, ID, file) {
                    $("#attachedfiles tr").each(function () {
                        if ($("td", this).eq(0).html() == file.name) {
                            alert(file.name + " already uploaded.");
                            $("[id*=FileUpload1]").fileUploadCancel(ID);
                            return;
                        }
                    });
                },
                'onComplete': function (event, ID, file, response, data) {
                    $("#attachedfiles").append("<tr><td>" + file.name + "</td><td><a href = 'javascript:;'>[x]</a></td></tr>");
                }
            });
        });

        $("#attachedfiles a").live("click", function () {
            var row = $(this).closest("tr");
            var fileName = $("td", row).eq(0).html();
            $.ajax({
                type: "POST",
                url: "CS.aspx/RemoveFile",
                data: '{fileName: "' + fileName + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () { },
                failure: function (response) {
                    alert(response.d);
                }
            });
            row.remove();
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table>
    <tr><td>To:</td><td><asp:TextBox ID="txtTo" runat="server"></asp:TextBox></td></tr>
    <tr><td>Subject:</td><td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td></tr>
    <tr><td>Body:</td><td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine"></asp:TextBox></td></tr>
    <tr><td></td><td><asp:FileUpload ID="FileUpload1" runat="server"/></td></tr>
    <tr><td></td><td><table id="attachedfiles"></table></td></tr>
    <tr><td></td><td><asp:Button ID="btnSend" runat="server" Text="Send" OnClick="btnSend_Click"/></td></tr>
    </table>
    </form>
</body>
</html>



i cant get value in code behind session variable and also error in .ascx file when we add files object.

[edit]Code blocks added - OriginalGriff[/edit]
Posted
Updated 20-Nov-12 22:16pm
v2
Comments
OriginalGriff 21-Nov-12 4:17am    
Where is the error occurring? Which line does it report?

1 solution

Always check that "files" and "postedFile" are not null!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900