FileUpload

Apr 13, 2006

    I have gotten FileUpload in VB.Net to work fine in saving a file to a web server folder but cannot find some examples on how to save the file as an image on sql200.  Can anyone point me in the write direction - thanks.

View 3 Replies


ADVERTISEMENT

FileUpload Control And MS SQL

Jun 1, 2006

I am trying to use the FileUpload control to save a filename to a SQL database. I'm using the OnUpdating event for my SQLDataSource to add the filename to the UpdateParameters. The OnUpdating event is firing but the FileName doesn't get added to the database. Any pointers as to why that might be would be very helpful.
Here's the code. Thanks much.
<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="File Upload Testing" %>
<script runat="server">
Sub Page_Load()
Response.Write("UpdateParameters(0)=" & dsLabel.UpdateParameters(0).Name & "<br />")
Response.Write("UpdateParameters(1)=" & dsLabel.UpdateParameters(1).Name & "<br />")
End Sub

Sub dsLabel_OnUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs)
Dim FileUploadControl As FileUpload = DetailsView1.FindControl("FileUpload1")
Dim strFileName As String = FileUploadControl.FileName
dsLabel.UpdateParameters(0).DefaultValue = strFileName
dsLabel.UpdateParameters(1).DefaultValue = Request.QueryString("rgstnID")
Response.Write("dsLabel.UpdateParameters(0).DefaultValue = " & dsLabel.UpdateParameters(0).DefaultValue & "<br />")
Response.Write("dsLabel.UpdateParameters(1).DefaultValue = " & dsLabel.UpdateParameters(1).DefaultValue & "<br />")
End Sub
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h1>File Upload</h1>
This page should allow me to use the FileUpload Control to save a filename to an MS SQL Database.<br />
<br />
&nbsp;<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
DataSourceID="dsLabel" Height="50px" Width="125px">
<Fields>
<asp:TemplateField HeaderText="File" SortExpression="labelName">
<EditItemTemplate>
<asp:FileUpload ID="FileUpload1" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("labelName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Button" ShowEditButton="True" />
</Fields>
</asp:DetailsView>
<br />
<br />
<asp:SqlDataSource ID="dsLabel" runat="server"
ConnectionString="Data Source=FILESERVER1;Initial Catalog=IM;Integrated Security=True"
OnUpdating="dsLabel_OnUpdating"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT labelName FROM tblProductRegistration WHERE (registrationID = @registrationID)"
UpdateCommand="UPDATE tblProductRegistration SET labelName = @LabelName WHERE (registrationID = @registrationID)">
<UpdateParameters>
<asp:Parameter ConvertEmptyStringToNull="True" Name="LabelName" />
<asp:QueryStringParameter Type="Int64" Name="registrationID" QueryStringField="rgstnID" />
</UpdateParameters>
<SelectParameters>
<asp:QueryStringParameter Name="registrationID" QueryStringField="rgstnID" />
</SelectParameters>
</asp:SqlDataSource>
</asp:Content>

View 2 Replies View Related

SQL Server DB And Fileupload Control

May 22, 2008

I have a project that is using an exsisting SQL DB that stores uploaded files and images into the DB.
I am trying to figure out how to take the file from the fileupload control and place it into the DB field.
Almost all the examples I've seen deal specifically with images but I will not know what the file type is. It could be an image, a word doc, and excel file, a text file ect.
I thought to use a INSERT statement but I wonder if that will work.
I know that fileupload.postedfile.saveas saves the file to a directory you name but that does not help me. I thought I could just use the fileupload.contents property in the Parameter add statement but that must not be an option as I cannot find and example of that usage besides that would just be too easy I guess.
Any help or code would be accepted with great gratituide. I realize that this is not the best way for performance but it is what it is and I cannot scrap the old DB I just have to make it work.
Thanks,
Ty

View 7 Replies View Related

FileUpload Control And SQL Server 2005.

Aug 15, 2006

Hello,
I have a FileUpload control on my webform. I would like a user to be able to upload a file to the server. Is there any way to store this file in SQL Server 2005?
Thanks
ASPSQL66

View 1 Replies View Related

Fileupload Inside A CreateuserWizard Control ?

Sep 7, 2006

HiHoping someone can help me , I am looking to add a file upload inside a createuserWizard but am banging my head at this stage I can get in working saving the file selected in the Fileupload into  a table on the database using a datatype "image" for the field.However
ideally I would like to save a string of the file path to the database
and save the  actual file to the filesystem of the webserver.The
problem for me is that this is inside a CreateUserWizard, I gather the
standard information and them have "extended" the wizard  by adding
another wizard step , which will include a FileUpload control. I need
to invoke the FileUpload when the user select the createUser button of
the CreateUserWizard control( CreateUserWizard1_CreatedUser in the aspx.cs)  I
am able to write the SQL that  allows save information from a textbox
to a database tabel but not able to write the functionality to 1.Uplaod file to webServer when user selects Create User button 2. Save this path in a table on the database.I've tried loads but cannot get it to work I'm using C# for this.  here's a scaled down version of my code with just teh CreateUserWizard which contains the fileUploadaspx ( Contains a create user Wizard which inturn contains a Fileupload) <%@ Page Language="C#" AutoEventWireup="true"  CodeFile="FORUMcreateuser.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 id="Head1" runat="server">    <title>Sign Up Page</title></head><body>    <form id="form1" runat="server" enctype="multipart/form-data">       
<atlas:ScriptManager id="MasterScriptManager"
EnableScriptGlobalization="false"
runat="Server"></atlas:ScriptManager>    <div>       
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server"
BackColor="White" BorderColor="#FFDFAD" BorderStyle='Solid'
BorderWidth='1px' Font-Names='Verdana' Font-Size='0.8em'
OnCreatedUser='CreateUserWizard1_CreatedUser'>            <WizardSteps>                <asp:WizardStep ID="CreateUserWizardStep0" runat="server">                    <table id="Table2" style='width: 100%'>                        <tr>                            <td style='color: blue'>                                <strong>Step 1 of 2</strong></td>                            <td style='color: white'>                                PlaceHolderBGColor</td>                            <td>                            </td>                        </tr>                        <tr>                            <td>                            </td>                            <td style='color: white'>                            </td>                            <td>                            </td>                        </tr>                        <tr>                            <td>                                First Name:</td>                            <td>                                <asp:TextBox runat="server" ID="txtFirstName" MaxLength="50" />                            </td>                            <td>                               
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator15" ControlToValidate="txtFirstName"                                     ErrorMessage="First Name is required." />                            </td>                        </tr>                        <tr>                            <td>                                Last Name:</td>                            <td>                                <asp:TextBox runat="server" ID="txtLastName" MaxLength="50" />                            </td>                            <td>                               
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator16" ControlToValidate="txtLastName"                                     ErrorMessage="Last Name is required." />                            </td>                        </tr>                        <tr>                            <td>                            </td>                            <td style='color: white'>                                PlaceHolderBGColor</td>                            <td>                            </td>                        </tr>                        <tr>                            <td>                                File:</td>                            <td>                                &nbsp;<asp:FileUpload ID="FileUpload1" runat="server" />                            </td>                            <td>                                &nbsp;</td>                        </tr>                        <tr>                            <td>                            </td>                            <td>                            </td>                            <td>                            </td>                        </tr>                    </table>                    <br />                </asp:WizardStep>                               <asp:CreateUserWizardStep ID="CreateUserWizardStep2" runat="server">                <ContentTemplate>                    <table>                        <tr>                            <th align="left" style='color: blue'>                                Step 2 of 2</th>                        </tr>                        <tr>                            <th align="left">                                MRS Login Details                            </th>                        </tr>                        <tr>                            <td>Username:</td>                            <td>                                <asp:TextBox runat="server" ID="UserName" />                               
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator9" ControlToValidate="UserName"                                     ErrorMessage="Username is required." />                            </td>                        </tr>                        <tr>                            <td>Password:</td>                            <td>                                <asp:TextBox runat="server" ID="Password" TextMode="Password" />                               
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator10" ControlToValidate="Password"                                     ErrorMessage="Password is required." />                            </td>                        </tr>                        <tr>                            <td>Confirm Password:</td>                            <td>                                <asp:TextBox runat="server" ID="ConfirmPassword" TextMode="Password" />                               
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator13" ControlToValidate="ConfirmPassword"                                     ErrorMessage="Confirm Password is required." />                            </td>                        </tr>                        <tr>                            <td>Email:</td>                            <td>                                <asp:TextBox runat="server" ID="Email" />                               
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator11" ControlToValidate="Email"                                     ErrorMessage="Email is required." />                            </td>                        </tr>                        <tr>                            <td>                                Recover Password Question:</td>                            <td>                                <asp:TextBox runat="server" ID="Question" />                               
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator12" ControlToValidate="Question"                                     ErrorMessage="Question is required." />                            </td>                        </tr>                        <tr>                            <td>                                recover Password Answer:</td>                            <td>                                <asp:TextBox runat="server" ID="Answer" />                               
<asp:RequiredFieldValidator runat="server"
ID="RequiredFieldValidator14" ControlToValidate="Answer"                                     ErrorMessage="Answer is required." />                            </td>                        </tr>                        <tr>                            <td colspan="2">                                 <asp:CompareValidator ID="PasswordCompare" runat="server" ControlToCompare="Password"                                       
ControlToValidate="ConfirmPassword" Display="Dynamic" ErrorMessage="The
Password and Confirmation Password must
match."></asp:CompareValidator>                            </td>                        </tr>                        <tr>                            <td colspan="2">                                <asp:Literal ID="ErrorMessage" runat="server" EnableViewState="False"></asp:Literal>                            </td>                        </tr>                    </table>                   
<asp:SqlDataSource ID="InsertExtraInfo" runat="server"
ConnectionString="<%$ ConnectionStrings:CONTACTSConnectionString
%>"                        InsertCommand="INSERT INTO [CLIENT]
([client_id], [First_Name], [Last_Name]) VALUES (@UserId, @FirstName,
@LastName)"                        ProviderName="<%$ ConnectionStrings:CONTACTSConnectionString.ProviderName %>">                        <InsertParameters>                           
<asp:ControlParameter Name="FirstName" Type="String"
ControlID="txtFirstName" PropertyName="Text" />                           
<asp:ControlParameter Name="LastName" Type="String"
ControlID="txtLastName" PropertyName="Text" />                        </InsertParameters>                                           </asp:SqlDataSource>                                    </ContentTemplate>                </asp:CreateUserWizardStep>                <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server">                </asp:CompleteWizardStep>            </WizardSteps>            <NavigationButtonStyle BackColor="White" BorderColor="#CC9966" BorderStyle='Solid'                BorderWidth="1px" Font-Names="Verdana" ForeColor="#990000" />            <HeaderStyle BackColor="#FFCC66" BorderColor="White" BorderStyle='Solid' BorderWidth='2px'                Font-Bold="True" Font-Size="0.9em" ForeColor="#333333" HorizontalAlign="Center" />            <CreateUserButtonStyle BackColor="White" BorderColor="#CC9966" BorderStyle='Solid'                BorderWidth="1px" Font-Names="Verdana" ForeColor="#990000" />            <ContinueButtonStyle BackColor="White" BorderColor="#CC9966" BorderStyle='Solid'                BorderWidth="1px" Font-Names="Verdana" ForeColor="#990000" />            <SideBarStyle BackColor="#990000" Font-Size="0.9em" VerticalAlign="Top" />            <TitleTextStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />            <SideBarButtonStyle ForeColor="White" />        </asp:CreateUserWizard>    </div>    </form></body></html> aspx.cs using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {    }    protected void CreateUserWizard1_CreatedUser(object sender, EventArgs e)    {        TextBox UserNameTextBox =            (TextBox)CreateUserWizardStep2.ContentTemplateContainer.FindControl("UserName");        SqlDataSource DataSource =            (SqlDataSource)CreateUserWizardStep2.ContentTemplateContainer.FindControl("InsertExtraInfo");        MembershipUser User = Membership.GetUser(UserNameTextBox.Text);        object UserGUID = User.ProviderUserKey;        DataSource.InsertParameters.Add("UserId", UserGUID.ToString());        DataSource.Insert();    }}  

View 1 Replies View Related

Using FileUpload To Store Image In SQL Database

Apr 24, 2008

Hi
I have a asp:FileUpload conponent that I am trying to use to retrieve a picture file from the clients pc and store it in a SQL database.
The table is called PropertyImage and it contains the following fields:
imgID (type = int - autoincrement); imgData (type = Image); imgTitle (type = VarChar); imgType (type = VarChar); imgLength (type = BigInt);
I have a button (Button1) which when clicked calls Button1_Click()
--------------------------------------------------protected void Button1_Click(object sender, EventArgs e)
{byte[] fileData = null;
Boolean status = false;if (FileUpload1 != null)
{
// Make sure the file has data.if ((FileUpload1.PostedFile != null) && (FileUpload1.PostedFile.ContentLength > 0))
{
// Get the filename.string fn = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
try
{
// Access the file stream and begin the upload. Store the file in a memory byte array.Stream MyStream = FileUpload1.PostedFile.InputStream;
long iLength = MyStream.Length;fileData = new byte[(int)MyStream.Length];MyStream.Read(fileData, 0, (int)MyStream.Length);
MyStream.Close();
}catch (Exception ex)
{ }
}
}SqlConnection connection = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\heidihomes.mdf;Integrated Security=True;User Instance=True");
try
{
connection.Open();SqlCommand sqlCmd = new SqlCommand("INSERT INTO PropertyImage (imgData, imgaTitle, imgType, imgLength) VALUES(@data,@title,@type,@length)");
SqlParameter param = new SqlParameter();
// String connectionString = new SqlConnection(sqlCmd, connection);
 param = new SqlParameter("@data", SqlDbType.Image);
param.Value = fileData;
sqlCmd.Parameters.Add(param);param = new SqlParameter("@title", SqlDbType.VarChar);
param.Value = fileData;
sqlCmd.Parameters.Add(param);param = new SqlParameter("@type", SqlDbType.VarChar);
param.Value = fileData;
sqlCmd.Parameters.Add(param);param = new SqlParameter("@length", SqlDbType.BigInt);
param.Value = fileData;
sqlCmd.Parameters.Add(param);
sqlCmd.ExecuteNonQuery();
connection.Close();status = true;
}catch (Exception ex){ }if (status)
{
UploadStatus.Text = "File Uploaded Successfully";Server.Transfer("Admin_PropertyView.aspx");
}
else
{UploadStatus.Text = "Uploaded Failed";
}
}
}
--------------------------------------------------
But when I click on the button, nothing happens.
Please could someone help me out here.  I have tried this a few times and still haven't come right.
Also, if there is something else wrong with the code, please let me know.
Thanking you in advance.

View 9 Replies View Related

Store Files In SQL From An ASP Page Using FileUpload

May 23, 2008

I am almost done with a simple page to have a user select a file (using the FileUpload object), give it a short description and associate it with an item from a listbox.  Thensave these pieces of data to a new row in a SQL DB.
My issue... 
The SQLSmd.ExecuteNonQuery FAILS...
I have got all the fields able to connect and almost save... but for the actual "document" field errors out.  The user can select any type of file (image, word, excel, Powerpoint, etc) for storage into the DB.  I am not storing a referance to a file or the path to a file but the actual file in SQL.In the DB I have the field (Document) set to a type of VarBinary(8000) in the table.  Here is thethe corrisponding code in my app... 
Dim bArray As Byte...bArray = FileUpload1.PostedFile.InputStream.ReadByte()... SQLCmd.Parameters.Add("@Document", Data.SqlDbType.VarBinary, 8000).Value = bArray...iReturn = SQLCmd.ExecuteNonQuery()
ERRORThe first section of the stact trace...
[InvalidCastException: Invalid cast from 'System.Byte' to 'System.Byte[]'.]   System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) +867   System.Byte.System.IConvertible.ToType(Type type, IFormatProvider provider) +37   System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) +408   System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType) +896

View 7 Replies View Related

Uploading A File To A SQL Database Via A Typed Dataset And Using The FileUpload Control.

Oct 2, 2006

I am trying to upload a file in ASP.net 2.0 to a SQL database using the FileUpload control. I am doing this by way of a typed dataset.Here is my code.Dim rta As New ResponseTableAdapterDim rdt As ResponseDataTable = rta.GetResponseByID(1)Dim rr As ResponseRow = rdt(0)Dim fs As New FileStream(fu.PostedFile.FileName, FileMode.Open, FileAccess.Read)Dim br As New BinaryReader(fs)Dim image() As Byte = br.ReadBytes(fs.Length)br.Close()fs.Close()rr.UploadFile = imagerr.NameFile = fs.Namerta.Update(rdt)The code runs without an error but afterwards I find that nothing has been stored in the UploadFile cell in the database but the file name has been stored in the NameFile cell in the database. Any ideas?Your help is much appreciated. James 

View 1 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved