By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,354 Members | 1,042 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,354 IT Pros & Developers. It's quick & easy.

How to get posted file from upload file or html in put file?

P: 1
Hi all..

my project is in c sharp
and must upload pictures to MySql DataBase

the uploadfile controle is included in asp form that i made

but the problem is that the uploadfile always get the Postedfile = null

i tried to use html input file but the same problem still


here's my code :

Expand|Select|Wrap|Line Numbers
  1. <%@ Page Language="C#" MasterPageFile="~/MasterPageB.master" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="Add_Pictures" Title="Untitled Page" %>
  2. <%@ MasterType TypeName="MasterPageB" %>
  3. <%@ Register assembly="MyFormView" namespace="MyFormView" tagprefix="asp" %>
  4. <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
  5.  
  6. <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolderB" Runat="Server">
  7.  
  8. <asp:MyForm ID="AddPictureMyForm" runat="server" method="post"
  9.         DataSourceID="picturesqlDataSource" Show_Cancel_button="true" 
  10.         DefaultMode="Insert" DataKeyNames="id" Visible="true" Width="75%" 
  11.         Height="390px">
  12.         <InsertItemTemplate>
  13.          <asp:Panel ID="InsertPanel" runat="server" BorderStyle="Solid" BorderWidth="2px"  
  14.            ScrollBars="Auto" Width="100%" Height="100%">
  15.            <table style="width:657px; height: 233px;" align="center">
  16.            <tr>
  17.               <td align="center" style="font-weight: bold; width: 98px; height: 30px;">
  18.                    &nbsp;</td>
  19.               <td style="height: 30px;" colspan="3">
  20.                     &nbsp;</td>
  21.            </tr>
  22.            <tr>
  23.             <td align="center" style="font-weight: bold; width: 98px; height: 30px;">
  24.                         <span style="color:Red">*</span><asp:Label ID="TitleLabel" runat="server" 
  25.                             Text="Title"></asp:Label>
  26.                     </td>
  27.                     <td style="height: 30px" colspan="3" >
  28.                         <asp:TextBox ID="TitleTextBox" runat="server" Height="22px" Width="175px" MaxLength="50"></asp:TextBox>
  29.                     </td>
  30.            </tr>
  31.            <tr>
  32.            <td align="center" style="font-weight: bold; width: 98px; height: 37px;">
  33.                         <asp:Label ID="DescriptionLabel" runat="server" Text="Description"></asp:Label>
  34.                     </td>
  35.                     <td style="height: 37px" colspan="3">
  36.                         <asp:TextBox ID="DescriptionTextBox" runat="server" Height="22px" Width="465px" MaxLength="250"></asp:TextBox>
  37.                     </td>
  38.            </tr>
  39.            <tr>
  40.              <td align="center" style="font-weight: bold; width: 98px; height: 30px;">
  41.                         <span style="color:Red">*</span><asp:Label ID="pathLabel" runat="server" 
  42.                             Text="path"></asp:Label>&nbsp;</td>
  43.                     <td style="height: 30px" colspan="3">
  44.                         <input ID="MyFile" runat="server" align="left" alt="rtl" 
  45.                             onclick="return filMyFile_onclick()" type="file" visible="False" />
  46.                             <asp:TextBox ID="pathTextBox" runat="server" Height="22px" MaxLength="100" 
  47.                             Width="467px" Visible="False"></asp:TextBox>
  48.                         <asp:FileUpload ID="FileUpload1" runat="server" />
  49.                     </td>
  50.            </tr>
  51.            <tr>
  52.                <td align="center" style=" font-weight: bold; width: 98px; height: 36px;">
  53.                         <asp:Label ID="ReferenceLabel" runat="server" 
  54.                             Text="Reference"></asp:Label>
  55.                         </td>
  56.                     <td style="height: 36px; width: 238px;" >
  57.                            <asp:TextBox ID="ReferenceTextBox" runat="server" Height="22px" MaxLength="100" 
  58.                                Width="178px"></asp:TextBox>
  59.  
  60.                      </td> 
  61.            </tr>
  62.            <tr>
  63.             <td align="center" style="font-weight: bold; width: 98px; height: 34px;">
  64.                         <span style="color:Red">*</span><asp:Label ID="TypeLabel" runat="server" 
  65.                             Text="type"></asp:Label>
  66.                         &nbsp;</td>
  67.                     <td style="height: 34px; width: 238px;">
  68.                         <asp:DropDownList ID="TypeDropDownList" runat="server" 
  69.                             DataSourceID="TypeSqlDataSource" DataTextField="name" 
  70.                             DataValueField="id" Height="22px" 
  71.                             ondatabound="TypeDropDownList_DataBound" Width="181px">
  72.                         </asp:DropDownList>
  73.                     </td>
  74.                     <td rowspan="4" align="center" style="width: 238px">
  75.                         <asp:Image ID="imgDB" runat="server" Visible="False" />
  76.                     </td>
  77.                     <td rowspan="4" style="width: 73px">
  78.                         &nbsp;</td>
  79.            </tr>
  80.            <tr>
  81.                <td align="left" style="font-weight: bold; width: 98px; height: 34px;">
  82.                         <asp:Label ID="anniversaryLabel" runat="server" Text="anniversary"></asp:Label>
  83.                     </td>
  84.                     <td style="width: 238px; height: 50px;">
  85.                         <asp:TextBox ID="anniversaryTextBox" runat="server" Height="22px" 
  86.                             MaxLength="15" Width="178px"></asp:TextBox>
  87.                         <asp:ImageButton ID="calendar_Date" runat="server" 
  88.                             ImageUrl="~/images/Calendar.png" />
  89.                         <cc1:CalendarExtender ID="AddMyCalendar" runat="server" Enabled="True" 
  90.                             FirstDayOfWeek="Saturday" Format="dd/MM/yyyy" PopupButtonID="calendar_Date" 
  91.                             PopupPosition="BottomRight" TargetControlID="anniversaryTextBox">
  92.                         </cc1:CalendarExtender>
  93.                     </td>
  94.            </tr>
  95.            <tr>
  96.                  <td align="center" style="font-weight: bold; width: 98px; height: 34px;">
  97.                         &nbsp;</td>
  98.                     <td style="width: 238px; height: 50px;">
  99.                         &nbsp;</td>
  100.            </tr>
  101.            </table> 
  102.            </asp:Panel>
  103.         </InsertItemTemplate>
  104.         </asp:MyForm>
  105.  
  106.  <asp:ImageButton ID="AddImageButton" runat="server" 
  107.         ImageUrl="~/images/controls/upload 1.gif"  
  108.         Height="30px" Width="119px" onclick="AddImageButton_Click1" />
  109.  
  110.  <asp:SqlDataSource ID="TypeSqlDataSource" runat="server"
  111.      ConnectionString="<%$ ConnectionStrings:info_con %>" 
  112.         ProviderName="<%$ ConnectionStrings:info_con.ProviderName %>" 
  113.  
  114.         SelectCommand="SELECT * FROM picture_type" >
  115.         </asp:SqlDataSource>
  116.  
  117.  <asp:SqlDataSource ID="picturesqlDataSource" runat="server" 
  118.          ConnectionString="<%$ ConnectionStrings:info_con %>" 
  119.          ProviderName="<%$ ConnectionStrings:info_con.ProviderName %>" 
  120.          InsertCommand="INSERT INTO pictures (title, description, type, path, reference, ac_id, anniversary) VALUES (@title, @description, @type, @path, @reference, 8, @anniversary)"  
  121.          SelectCommand="">
  122.          <InsertParameters>
  123.           <asp:Parameter Name="title" />
  124.           <asp:Parameter Name="description" />
  125.           <asp:Parameter Name="type" />
  126.           <asp:Parameter Name="path" />
  127.           <asp:Parameter Name="reference" />
  128.           <asp:Parameter Name="anniversary" />
  129.         </InsertParameters>
  130.         <SelectParameters>
  131.         <asp:Parameter Name="path" />
  132.         </SelectParameters>
  133.     </asp:SqlDataSource>
  134. </asp:Content>
  135.  
Expand|Select|Wrap|Line Numbers
  1.  using System;
  2. using System.Collections;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Linq;
  6. using System.Web;
  7. using System.Web.Security;
  8. using System.Web.UI;
  9. using System.Web.UI.HtmlControls;
  10. using System.Web.UI.WebControls;
  11. using System.Web.UI.WebControls.WebParts;
  12. using System.Xml.Linq;
  13. using MySql.Data.MySqlClient;
  14. using Webdll;
  15. using System.Collections.Generic;
  16. using System.IO;
  17.  
  18. public partial class Add_Pictures : BasicPage
  19. {
  20.     protected void Page_Init(object sender, EventArgs e)
  21.     {
  22.         base.SetMaster(Master, AddPictureMyForm);
  23.  
  24.     }
  25.     protected void Page_Load(object sender, EventArgs e)
  26.     {
  27.         if (!this.IsPostBack)
  28.         {
  29.             Master.Labelb = "Adding";
  30.         }
  31.     }
  32.     protected void Page_SaveStateComplete()
  33.     {
  34.         if ((AddPictureMyForm.Visible == true) && (AddPictureMyForm.FooterRow != null))
  35.         {
  36.             List<ControlsToValidate> list = new List<ControlsToValidate>();
  37.             TextBox tx1 = (TextBox)AddPictureMyForm.FooterRow.FindControl("TitleTextBox");
  38.             TextBox tx2 = (TextBox)AddPictureMyForm.FooterRow.FindControl("DescriptionTextBox");
  39.             TextBox tx3 = (TextBox)AddPictureMyForm.FooterRow.FindControl("pathTextBox");
  40.             TextBox tx4 = (TextBox)AddPictureMyForm.FooterRow.FindControl("ReferenceTextBox");
  41.             TextBox tx5 = (TextBox)AddPictureMyForm.FooterRow.FindControl("anniversaryTextBox");
  42.  
  43.  
  44.             ImageButton bt_add = AddImageButton;
  45.  
  46.             if (bt_add != null)
  47.             {
  48.                 list.Add(new ControlsToValidate(tx1, CDataType.text, true, 50));
  49.                 list.Add(new ControlsToValidate(tx2, CDataType.text, false, 250));
  50.                 list.Add(new ControlsToValidate(tx3, CDataType.text, true, 100));
  51.                 list.Add(new ControlsToValidate(tx4, CDataType.text, false, 100));
  52.                 list.Add(new ControlsToValidate(tx5, CDataType.date, false, 15));
  53.  
  54.                 ValidateControls(bt_add, list, message_type.alert);
  55.             }
  56.  
  57.         }
  58.     }
  59.  
  60.  
  61.     private void WriteToFile(string FileName, ref byte[] Buffer)
  62.     {
  63.         FileStream fs = new FileStream(FileName, FileMode.Create);
  64.         fs.Write(Buffer, 0, Buffer.Length);
  65.         fs.Close();
  66.     }
  67.     private int WriteToDB(string fileName, ref byte[] Buffer)
  68.     {
  69.         picturesqlDataSource.SelectCommand = "SELECT id, COUNT(*) AS count FROM pictures WHERE path = " + fileName + " GROUP BY id;";
  70.         DataView dv; DataRowView drv;
  71.         dv = (DataView)picturesqlDataSource.Select(DataSourceSelectArguments.Empty);
  72.         drv = dv[0];
  73.         if (Convert.ToInt32(drv["count"]) > 0)
  74.         { ScriptManager.RegisterStartupScript(this, this.GetType(), this.ToString(), @"<script language=""JavaScript"">window.alert('Duplicate in picture'); </script>", false); }
  75.         else
  76.         {
  77.             string anniversary = "";
  78.             try
  79.             {
  80.                 DateTime dt = Convert.ToDateTime(((TextBox)AddPictureMyForm.FindControl("anniversaryTextBox")).Text);
  81.                 anniversary = dt.ToString("yyyy-MM-dd");
  82.             }
  83.             catch { }
  84.  
  85.  
  86.             picturesqlDataSource.InsertParameters["title"].DefaultValue = ((TextBox)AddPictureMyForm.FindControl("TitleTextBox")).Text;
  87.             picturesqlDataSource.InsertParameters["description"].DefaultValue = ((TextBox)AddPictureMyForm.FindControl("DescriptionTextBox")).Text;
  88.             picturesqlDataSource.InsertParameters["path"].DefaultValue = fileName;
  89.             picturesqlDataSource.InsertParameters["reference"].DefaultValue = ((TextBox)AddPictureMyForm.FindControl("ReferenceTextBox")).Text;
  90.             picturesqlDataSource.InsertParameters["type"].DefaultValue = ((DropDownList)AddPictureMyForm.FindControl("TypeDropDownList")).SelectedValue;
  91.             picturesqlDataSource.InsertParameters["anniversary"].DefaultValue = anniversary;
  92.             //picturesqlDataSource.InsertParameters["Data"].DefaultValue = Buffer.ToString();
  93.  
  94.             try  // test inesrt command
  95.             {
  96.                 picturesqlDataSource.Insert();
  97.                 Action_status = event_status.success;
  98.                 ScriptManager.RegisterStartupScript(this, this.GetType(), this.ToString(), @"<script language=""JavaScript"">window.alert('Successfully Done'); </script>", false);
  99.                 picturesqlDataSource.SelectCommand = "SELECT id, COUNT(*) AS count FROM pictures WHERE id = (SELECT MAX(id) FROM pictures) GROUP BY id";
  100.                 dv = (DataView)picturesqlDataSource.Select(DataSourceSelectArguments.Empty);
  101.                 drv = dv[0];
  102.             }
  103.             catch
  104.             { ScriptManager.RegisterStartupScript(this, this.GetType(), this.ToString(), @"<script language=""JavaScript"">window.alert('Error in inserting '); </script>", false); }
  105.         }
  106.         //Get Id
  107.  
  108.         int id = Convert.ToInt32(drv["id"]);
  109.         return id;
  110.     }
  111.  
  112.     protected void TypeDropDownList_DataBound(object sender, EventArgs e)
  113.     {
  114.         ListItem li = new ListItem("select a type", "0");
  115.         ((DropDownList)sender).Items.Insert(0, li);
  116.     }
  117.     private string GetMyName()
  118.     {
  119.         // Get the script name
  120.         string strScript = Request.ServerVariables["SCRIPT_NAME"];
  121.  
  122.         // Get position of last slash
  123.         int nPos = strScript.LastIndexOf("/");
  124.  
  125.         // Get everything after slash
  126.         if (nPos > -1)
  127.             strScript = strScript.Substring(nPos + 1);
  128.  
  129.         return strScript;
  130.     }
  131.     protected void AddImageButton_Click1(object sender, ImageClickEventArgs e)
  132.     {
  133.         Action_status = event_status.fail;
  134.         FileUpload PicUpload = (FileUpload)AddPictureMyForm.FindControl("FileUpload1");
  135.         if (((DropDownList)AddPictureMyForm.FindControl("TypeDropDownList")).SelectedIndex == 0)
  136.         { ScriptManager.RegisterStartupScript(this, this.GetType(), this.ToString(), @"<script language=""JavaScript"">window.alert('must choose a type'); </script>", false); return; }
  137.  
  138.         if (PicUpload.PostedFile == null) { ScriptManager.RegisterStartupScript(this, this.GetType(), this.ToString(), @"<script language=""JavaScript"">window.alert('Error'); </script>", false); return; }
  139.  
  140.         HttpPostedFile myFile = PicUpload.PostedFile; // Get a reference to PostedFile object
  141.         int myFileLen = myFile.ContentLength;  // Get size of uploaded file
  142.  
  143.         if (myFileLen > 0)
  144.         {
  145.             byte[] myData = new byte[myFileLen]; // buffer to read
  146.             myFile.InputStream.Read(myData, 0, myFileLen); //read uploaded file from stream
  147.             string Filename = Path.GetFileName(myFile.FileName);
  148.             WriteToFile(Server.MapPath(Filename), ref myData);
  149.             int FileID = WriteToDB(Filename, ref myData);
  150.  
  151.             ((Image)AddPictureMyForm.FindControl("imgDB")).ImageUrl = GetMyName() + "?FileID=" + FileID.ToString();
  152.             ((Image)AddPictureMyForm.FindControl("imgDB")).Visible = true;
  153.         }
  154.     }
  155.     protected void filMyFile_onclick(object sender, ImageClickEventArgs e)
  156.     {
  157.         HtmlInputFile PicUpload = (HtmlInputFile)AddPictureMyForm.FindControl("MyFile");
  158.         if (PicUpload.PostedFile != null)
  159.         {
  160.  
  161.         }
  162.         else
  163.         { }
  164.     }
  165. }
  166.  
can any body help me Please...

thanks :)
Feb 2 '11 #1
Share this Question
Share on Google+
1 Reply


Frinavale
Expert Mod 5K+
P: 9,731
I'm not sure what MyForm is?
Upload controls (including the HTML input type=file control) will not work if you are using UpdatePanels in your forum (which I don't see in your code, but I'm not sure what MyForm is)...
Feb 7 '11 #2

Post your reply

Sign in to post your reply or Sign up for a free account.