473,396 Members | 1,706 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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

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
1 3667
Frinavale
9,735 Expert Mod 8TB
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

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

Similar topics

6
by: Giulio Neri | last post by:
Hi, I have a short basic script to upload files. It works fine with small files, but with longer files it gets stuck. Here's the fragment, the input file is loaded in "$file" from an HTML form...
7
by: Go USA! Go Israel! | last post by:
I was wondering if the following was possible: Instead of using a frameset which references other individual HTML files, have the <SPAN> tag reference another HTML file, which is placed within...
10
by: $kr1p7_k177y | last post by:
-Without using frames. -- .............................................................................. Chase after truth like hell and you'll free yourself, even though you never touch...
11
by: Jake j | last post by:
Yes, this is a simple and straightforward thing to do as long as the .js file doesn't use a function. When I try a script with a function in a js file I can't get it to work (though it works fine...
0
by: Dhanasankar S via DotNetMonster.com | last post by:
Hai friends, Please give me an idea to read the content in the body part of a HTML file from another HTML file using Javascript. -- Message posted via http://www.dotnetmonster.com
2
by: zorro | last post by:
Hello, When I upload an image to the server I get the message: Warning: Only -1 bytes were written, expected to write 547 The server phpinfo lists : file_uploads On
1
by: John Wolff | last post by:
I’m trying to upload a file to a Web Service. I have to submit the file using a standard HTML form with the <input type=“file” /tag. Ultimately, we are submitting the file from a Flash 8...
1
by: cssExp | last post by:
hi, Is there a way to check extension of the file path of file upload input field, like if its .jpg, .exe etc.?
1
by: ganesandeiav | last post by:
Dear frnds I am using jsp.I have a problem file upload using html control.I want filter seleted file such as *.gif&*.jpeg images .It should be list out jpeg gif image only. iam try this code but...
1
by: yemen2007 | last post by:
hi ever one. i have problem in my html file. i have header file , footer file, and index file. i want compile the header , and footer in the index file use include file put it is not work. this my...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.