473,626 Members | 3,952 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

1 New Member
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 3671
Frinavale
9,735 Recognized Expert Moderator Expert
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
2530
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 as usual. .... $img_str = fread(fopen($file, "r"), filesize($file)); $data = addslashes($img_str);
7
7661
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 that portion of the screen? I know how frames work. I hate frames. I like the SPAN tag, and I would like to be able to change the text within that portion of the page.
10
4005
by: $kr1p7_k177y | last post by:
-Without using frames. -- .............................................................................. Chase after truth like hell and you'll free yourself, even though you never touch its coat-tails. -Clarence Darrow
11
5578
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 within the html file). I'm guessing that there's some syntax or convention I'm not doing right. What I most need is an example. Can someone write a js file with an alert command, for example, to keep it simple. Perhaps something like: var...
0
254
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
4304
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
31520
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 application that uses Macromedia’s flash.net.FileReference class. The FileReference class behaves like a standard HTML form with the file input tag. I know there are other options for submitting files through Web Services, but we’re not able...
1
3073
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
3466
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 display the all files only <form method="post" ACTION="upload.jsp" name="uploadForm" ENCTYPE="multipart/form-data"> <input id="uploadfile" name="uploadfile" type="file" accept="image/gif,image/png">
1
2235
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 code.so plz hellp me this inside the footer.html <a href="contact_info.html">Contact Us</a> <a href="copyright_info.html">Copyright &copy; 2000-2002</a> <a href="about_us.html">Tailspin Toys</a> this inside the header.html
0
8199
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8705
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8638
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8505
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7196
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development projectplanning, coding, testing, and deploymentwithout human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4092
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
1811
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1511
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.