Upload

Jun 24, 2008

how to upload data from excel sheet to table in sql server is there any command for that

View 1 Replies


ADVERTISEMENT

Why Is SSIS Upload From FoxPro Way Slower That A Upload Using DTS?

Oct 20, 2006

I am rewritting our DTS that upload tables in FoxPro to SQL Server using SSIS. I am finding the that SSIS is way slower. My uploads using DTS take just 7 minutes where doing the same thing in SSIS is taking 1 hour 15 minutes.

View 2 Replies View Related

Upload Doc

Mar 9, 2004

Hi Guys,

I have one question, must be simple for you guys. I want to upload .pdf document into the SQL server database.

I have one question, that which data type I should use. Should I use TEXT or IMAGE.

Could you please tell me which data type I should use and why?

Thanks for your help in advance.

View 2 Replies View Related

Upload An Image ....?!

Dec 24, 2006

I used upload image feature and below is the code that I used. The image is stored in a folder. I want to save the image in sql database. I create the database which is “database�, and I create a table which is “user�. User table has auto “id� field and “image� field. I want to save the image in the image field. I need your help to do the other codes.
 
I am using asp.net with VB
 
This is what I did so far:
============================
Partial Class upload
    Inherits System.Web.UI.Page
    Dim strFileName As String
 
    Protected Sub btnupload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnupload.Click
        UploadImage()
    End Sub
    Sub UploadImage()
 
        If Not (fileupload1.PostedFile Is Nothing) Then 'Check to make sure we actually have a file to upload
 
            Dim strLongFilePath As String = fileupload1.PostedFile.FileName
            Dim intFileNameLength As Integer = InStr(1, StrReverse(strLongFilePath), "")
            strFileName = Mid(strLongFilePath, (Len(strLongFilePath) - intFileNameLength) + 2)
 
            Select Case fileupload1.PostedFile.ContentType
                Case "image/pjpeg", "image/jpeg" 'Make sure we are getting a valid JPG image
                    FileUpload1.PostedFile.SaveAs(Server.MapPath(" estimages") & strFileName)
                    lbstatus.Text = strFileName & " was uploaded successfully to: " & Server.MapPath(" estimages") & strFileName
 
                Case Else
                    'Not a valid jpeg image
                    lbstatus.Text = "Not a valid jpeg image"
            End Select
 
            InsertToDatabase()
        End If
 
 
    End Sub

End class

View 1 Replies View Related

Trying To Upload A Picture To Sql

Sep 23, 2007

I am using the article, "
Storing Binary Files Directly in the Database Using ASP.NET 2.0 By Scott Mitchell "
 
http://aspnet.4guysfromrolla.com/articles/120606-1.aspx
I have tried to modify the code and my datatable to replicate the function, but I am getting an error, "MIMEType" is not a SQL Parameter
 
An SqlParameter with ParameterName 'Type' is not contained by this SqlParameterCollection.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.IndexOutOfRangeException: An SqlParameter with ParameterName 'Type' is not contained by this SqlParameterCollection.Source Error:



Line 53:
Line 54: 'Specify the values for the MIMEType and ImageData parameters
Line 55: e.Command.Parameters("Type").Value = MIMEType
Line 56:
Line 57: 'Load FileUpload's InputStream into Byte arraySource File: E:homeDefaultetances.ushtdocshomeadminaddNews.aspx    Line: 55
Code: Protected Sub AddNewsBut_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If Page.IsValid Then
InsertDs.Insert()
Response.Redirect("~/news/default.aspx")
End If

End Sub

Protected Sub InsertDs_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs)
'Reference the FileUpload control


'Make sure a file has been successfully uploaded
If UploadedFile.PostedFile Is Nothing OrElse String.IsNullOrEmpty(UploadedFile.PostedFile.FileName) OrElse UploadedFile.PostedFile.InputStream Is Nothing Then
Label1.Text = "If there is no photo of this event, please use a stock photo if you have none available. Else, please upload a photo of the event."
e.Cancel = True
Exit Sub
End If

'Make sure we are dealing with a JPG or GIF file
Dim extension As String = Path.GetExtension(UploadedFile.PostedFile.FileName).ToLower()
Dim MIMEType As String = Nothing

Select Case extension
Case ".gif"
MIMEType = "image/gif"
Case ".jpg", ".jpeg", ".jpe"
MIMEType = "image/jpeg"
Case ".png"
MIMEType = "image/png"

Case Else
'Invalid file type uploaded
Label1.Text = "Please use the correct file type: .jpg, .jpe, .gif, or .png."
e.Cancel = True
Exit Sub
End Select

'Specify the values for the MIMEType and ImageData parameters
e.Command.Parameters("Type").Value = MIMEType

'Load FileUpload's InputStream into Byte array
Dim imageBytes(UploadedFile.PostedFile.InputStream.Length) As Byte
UploadedFile.PostedFile.InputStream.Read(imageBytes, 0, imageBytes.Length)
e.Command.Parameters("Photo").Value = imageBytes

End Sub Please help.

View 1 Replies View Related

Upload Database

Oct 22, 2007

I created a website a year ago. I remember I need to download something from Microsoft (some kind of sql admin thing), which allows me to convert my database in the Express Visual Web developer to sql file, then I can copy those sql commands into my web hosting company's sql admin window to upload the database online. I forgot what things I should download from Microsoft? Please help.

View 1 Replies View Related

Upload Pictures

Oct 22, 2007

I am building this project and for all the data i put in to the DB Title,Author, etc.... ineed to also add a picture of the book.  I terms on space what is the best way to do this?  In the DB? Or ref a folder?  If so does anyone have sample code for each.
ThanksMike

View 23 Replies View Related

File Upload Help

Dec 11, 2007

Hi, I am trying to upload a file to database.
I have used the following code, every loads good to the database apart from the image, does it go anywhere?
I have created a column in the table called 'FileUploadAdvert' and made it an image?
Any ideas where I'm going wrong?
ThanksGordon 
Protected Sub btnAdvertSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdvertSubmit.ClickDim dashDataSource As New SqlDataSource()dashDataSource.ConnectionString = ConfigurationManager.ConnectionStrings("DashConnectionString1").ToString()
dashDataSource.InsertCommandType = SqlDataSourceCommandType.Text
dashDataSource.InsertCommand = "INSERT INTO tblAdvert (AdvertOwner, AdvertName, TopLeftH, TopLeftV, Height, Width, ToolTip, WebLink, AcceptTerms, DateTimeStamp, IPAddress) VALUES (@AdvertOwner, @AdvertName, @TopLeftH, @TopLeftV, @Height, @Width, @ToolTip, @WebLink, @AcceptTerms, @DateTimeStamp, @IPAddress)"dashDataSource.InsertParameters.Add("AdvertOwner", txtName.Text)
dashDataSource.InsertParameters.Add("AdvertName", txtCompName.Text)dashDataSource.InsertParameters.Add("TopLeftH", DropDownAccross.Text)
dashDataSource.InsertParameters.Add("TopLeftV", DropDownDown.Text)dashDataSource.InsertParameters.Add("Height", DropDownHeight.Text)
dashDataSource.InsertParameters.Add("Width", DropDownWidth.Text)dashDataSource.InsertParameters.Add("ToolTip", txtOver.Text)
dashDataSource.InsertParameters.Add("Weblink", txtURL.Text)dashDataSource.InsertParameters.Add("AcceptTerms", CheckBoxAgree.Checked)
dashDataSource.InsertParameters.Add("IPAddress", Request.UserHostAddress.ToString)dashDataSource.InsertParameters.Add("DateTimeStamp", DateTime.Now)
If Not FileUploadAdvert.PostedFile Is Nothing ThenDim filepath As String = FileUploadAdvert.PostedFile.FileName
Dim pat As String = "\(?:.+)\(.+).(.+)"Dim r As Regex = New Regex(pat)
'runDim m As Match = r.Match(filepath)
Dim file_ext As String = m.Groups(2).Captures(0).ToString()Dim filename As String = m.Groups(1).Captures(0).ToString()
Dim file As String = filename & "." & file_ext
'save the file to the server FileUploadAdvert.PostedFile.SaveAs(Server.MapPath(".") & file)
lblStatus.Text = "File Saved to: " & Server.MapPath(".") & fileEnd If
 Dim rowsAffected As Integer = 0
Try
rowsAffected = dashDataSource.Insert()Catch ex As Exception
Server.Transfer("Register_Fail.aspx")
Finally
dashDataSource = Nothing
End Try
If rowsAffected <> 1 ThenServer.Transfer("Register_Fail.aspx")
ElseServer.Transfer("Register_Complete.aspx")
End If
End Sub

View 4 Replies View Related

File Upload To SQL In 2.0 VB

May 2, 2006

Can anyone give me an example of how to Upload a file to SQL in asp.net 2.0 using VB?
 
Thanks
Randy

View 2 Replies View Related

How To Upload MS SQL 7.0 To The Server

Apr 10, 1999

We have to upload the database from the production server to the ineternet server. We are making a backup and restoring the databse on the internet sever, this requiers somebody on the serrver to restore the database manually. Is there any other way? Can i overwrite or update the new design the database on the server in any other way? Thanks.

View 1 Replies View Related

Sql Xml Bulk Upload

Mar 2, 2006

i am loading xml files present in a folder to sql server. i am doing this by means of ActiveX script (VB). i am passing every xml file and its schema definition file as parameter. later this script automatically create a table in script and loads the the data to database. for every xml in that foleder there is only one xsd.--------this was my intention.
but when i run the DTS script error is coming like "Error source: schema mapping, unable to upload xsd file".

is that always necessary to add
(xlmns:sql "urn:schemas-microsoft-com:mapping-schema") in its schema definition file.

View 1 Replies View Related

Data Upload

Dec 10, 2007

Hello!!
i need to upload a csv file to sql server, i am trying to load using bcp or bulk load, but the files has null columns, so i guess, that's why the program is displaying error.

my table is as follows:

PKCOLUMN TYPESIZENULLABLE
-----------------------------------------------
PKObject_idint 4NO
SO varchar 4NO
FISY smallint 2NO
Segment_idvarchar 3NO
SubSeg_idvarchar 3NO
Line_idvarchar 4NO
Level smallint 2NO
Type varchar 1NO
WWB_id varchar 3YES
SC_id varchar 6YES
PL_id varchar 9YES
PS_id varchar 12YES
PSS_id varchar 18YES
Material_idvarchar 18YES
WWCC_id varchar 2YES


THE OBJECT ID IS THE IDENTIFIER, SO IT SHOULD UPLOAD AUTOMATICALLY

MY FILE IS SOMETHING LIKE THIS:

SOFYSEGSUBSRNIVTIPOWWBSCPLPSPSSMATWWCC
45002008100110R16E102102120102120159102120159BBT102120159BBT100111300081NULL
45002008100110R16E102102120102120159102120159BBT102120159BBT100111300084NULL
45002008100110R16E102102705102705453102705453CIO102705453CIO100282300180NULL
45002008100110R16E102102705102705453102705453CIQ102705453CIQ100284300182NULL
45002008100110R16E102102705102705453102705453CIR102705453CIR100285300183NULL
45002008100110R16E102102120102120167102120167CIF102120167CIF100255300256NULL
45002008100110R16E102102705102705453102705453CJB102705453CJB103026300279NULL
45002008100110R16E102102705102705453102705453CIP102705453CIP100283300726NULL
45002008100110R16E102102120102120167102120167BED102120167BED100249300922NULL
45002008100110R16E102102120102120164102120164BDM102120164BDM103231301189NULL
45002008100110R16E102102120102120159102120159BBT102120159BBT100114301730NULL
45002008100110R16E102102443102443542102443542DFJ102443542DFJ102704301731NULL
45002008100110R16E102102705102705453102705453CIP102705453CIP100283301882NULL
45002008100110R14E102102120102120167102120167CIINULLNULLNULL
45002008100110R16E102102120102120159102120159BBT102120159BBT100111302346NULL
45002008100110R16E102102120102120159102120159BBT102120159BBT100111302347NULL
45002008100110R16E102102120102120159102120159BBT102120159BBT100111302349NULL


the first colums(identifier/object id) doesnt appear in the file, since it is supposed to be set automatically.
the last column is a null value.

Do you have any ideas??
why is it displayiing me an error?
which is the easiest way to upload the file??

thanx in advance

View 1 Replies View Related

How To Upload More Than One Field?

Jul 20, 2005

If I need to upload a single value from some singular query to the localvariable it may be like this:set @var = (select F from T where...)Next, what to do if I need more than one?Is it necessary to create a cursor, then open it, fetch and so on? Or may besomething likeset @var1, @var2 = (select F1, F2 from T where...)Thank you.

View 2 Replies View Related

How To Upload Table To Sql?

Jul 20, 2005

How to upload a content of a table into sql-file (the set of INSERTs)using standard MSSQL utilities?*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 2 Replies View Related

How To Upload A Table As Sql?

Jul 20, 2005

How to upload a content of a table into sql-file (as a set of INSERTs)using standard utilities?*** Sent via Developersdex http://www.developersdex.com ***Don't just participate in USENET...get rewarded for it!

View 2 Replies View Related

About XML Upload To Database

Jun 7, 2007

HI

Can anyone tell me how to upload a xml file in a table.I have uploaed text,csv,xel file but never xml.

just want to know how to upload, and when,why should we use xml file for data

thanks

sandipan

View 1 Replies View Related

Upload File

May 5, 2008

Hello

I am using Microsoft SQL Server Management Studio Express and want to insert a row into a table. The table (Pictures) has the following columns: ID (int), Filename (varchar), Data (varbinary).

INSERT INTO Pictures(ID, Filename, Data) VALUES
(12, 'photo.jpg', C:photo.jpg);


The statement above does not work. How do you do it?

Thank you

View 1 Replies View Related

Incremental Upload

Sep 10, 2007

I have done an bulk upload and I would like to start doing incremental uploads. I just want to upload only the new records that have been added to my data source ( free foxpro tables ). Can anybody point me to an example or info to accomplish this.

Thanks,
Sergio

View 6 Replies View Related

Data Upload

Jan 31, 2008

Simple question: How do I import/upload/insert data into a new database using MS SQL Server Management Studio Express, from a source like MSAccess or another SQL DB? I currently have a sample sql db (sample.bak), but unless I originally had it in MS SQL Server Management Studio Express it doesn't appear to want to restore it.

View 1 Replies View Related

Upload SQL Database To Server

Sep 19, 2006

Okay, I am still really new at this so nobody laugh if this seems simple stupid.  I created a little web page and while working on the project created a new database by right clicking on my app and clicking "Add New item" then choosing SQL Database.  I added tables and everything was working just dandy on my machine.  I FTP'd the files up to my web server and am now getting an error.  SQL is installed on the server, but I have a couple of questions.1. Does SQL have to be installed on the server if you create one of these databases by doing the Add New Item button?2. After Uploading it to a server with SQL installed, the database shows in my App Data folder, but gives me an error.  What needs done to move this database to the server besides uploading it?Here is my error:An error has occurred while establishing a connection to the server. When connecting to SQL Server 2005, this failure may be caused by the fact that under the default settings SQL Server does not allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)  

View 11 Replies View Related

How Do I Upload A MSDE Database

Sep 26, 2006

Downloaded and installed MSDE and just finished creating a
website using the Community Starter Kit.  I'm used to working with Access
Databases and this is my first experience with anything SQL.  Can someone
provide my with some guidance as to what I need to do to upload the MSDE
Database to a server.  Can I just upload the files like an Access Database
or is this more involved.  Thanks for you help.

View 5 Replies View Related

Store A File Upload Into DB

Sep 10, 2007

Can someone please direct me to a discussion on which version of SQL Server allows a file to be stored in a db field and how this is accomplished as well as how the file is then retrieved with asp.net VB from the DBthanksMilton

View 16 Replies View Related

Upload File Only Works For Dbo

Nov 6, 2007

Hi there,
My problem is that the upload works in testing for our asp.net site only for dbo. Being mindful of security, I would prefer not use this account to execute all sp_/sql. One solution could be using impersonation only in the content management system where the uploading is done, this is code in web.config:
  <location path="Manage.aspx">    <system.web>    <identity impersonate="true" userName="dbo" password="****" />      <authorization>        <deny users="?" />      </authorization>    </system.web>  </location>
To do this I would have to change the dbo password as set up by previous employee, not a real dba so not sure of the implications (enough permissions to be dangerous though;). Is the above impersonation ok, or should I redo logins security in sql? Thanks.

View 1 Replies View Related

Please Help Me... How Can I Upload Image Into My Sql Database

Nov 12, 2007

 Please help me... How can i upload image into my sql database in a basic way... thanks....

View 6 Replies View Related

Upload Dataset To SQL Server

Jun 2, 2008

Hello..I have around 460 rows of data in my dataset. I have to upload them into an empty table that already exists in SQL server. Can somebody help me with it?

View 7 Replies View Related

Sql 2000 Upload To A 2005 Sql DB?

Jun 5, 2008

Hi all, I am using ixwebhosting.com for a host and they say they are using sql 2005 servers, well any ways I have sql 2005 express edition, and sql 2000, I am able to export data from mysql2005 express using my 2000, but am having issues tryig to upoad the data to the 2005 sql server on the web host company. Any ideas on how to fix this or a workaround would be nice.Thanks All
Jonny

View 6 Replies View Related

Upload Path To Sqlserver

Nov 30, 2003

hi,

i want to ask how to save the path of the upload file (not the image) to the database?

ex : client upload from his/her computer, the path is c:/Program files/image.jpg

then the upload file is saved on the web server in location c:/intepub/wwwroot/imageGallery

then i just want to save the path c:/intepub/wwwroot/imageGallery/image1.jpg at my sqlserver
so that everytime an image is req, it's just search the path and display it

and the performance is better when i use path or save the image as binary file in sql server?

do know articles or link about this?

thank you again,
erick

View 2 Replies View Related

Deploying Web App, Which SQL Files Do I Upload?..

Nov 24, 2004

I'm working on a web application that uses SQL Server 2000. Once I'm ready to upload my website to a production server, I need to know how to upload my SQL Server database files to the server. Are there actual files that can be uploaded? I've only deployed a website that works with MySQL to a production server, and there were no files to upload... the database had to be created on the server, and then the data itself had to be exported to text files (on my computer), then imported/uploaded to the production server using SQL statements...

How do I do this?

Thanks~

View 2 Replies View Related

Upload .xls File To SQL Server

Aug 9, 2005

Here's what I have to do:1. Allow user to locate a .xls file on their machine2. Upload this .xls data into an existing table on a remote SQL ServerI can pull the file from my local machine to another directory on the local machien, but can't figure out have to configure the saveas() to save on the remote db server.It seems you have to save the the db server first on the hard drive, then you can insert the .xls file data into the table.Here's my code so far that works to save on the local machine to another directory on that local machine:Dim getmyFile As HttpPostedFile = myfile.PostedFileIf IsNothing(getmyFile) ThenLabel2.Text = "Please select a file to upload"ElseIf getmyFile.ContentLength = 0 ThenLabel2.Text = "Cannot upload zero length File"ElseDim ServerFileName As String = Path.GetFileName(myfile.PostedFile.FileName)getmyFile.SaveAs("C:TestSaving" & ServerFileName)Label2.Text = "Successful upload to C:TestSaving" & ServerFileNamesCon1.Open()Dim strSQL As StringDim err As IntegerstrSQL = "Insert into ActivityTest Select * FROM OPENROWSET"strSQL &= "('Microsoft.Jet.OLEDB.4.0','Excel 8.0;Database=D: esting.xls;"strSQL &= "HDR = YES ','SELECT * FROM [Sheet1$]')"Label3.Text = strSQL.ToString()Dim cmd As New SqlCommand(strSQL, sCon1)Trycmd.ExecuteNonQuery()err = "Select @@Error"If err <> 0 ThenLabel4.Text = err.ToString()ElseLabel4.Text = "No Error...line 91!"End IfCatch ex As ExceptionLabel2.Text = "Line 82 Error Updating Table: "Label2.Text &= ex.MessageFinallysCon1.Close()End TryEnd IfThanks for the help in advance!!!!

View 1 Replies View Related

Cannot Upload File To Database

Mar 16, 2006

  Can anyone correct my code?I will like to add a url to my database and upload my image to web server.txtAddTitle will become my title nametxtFileName allow user to type in image name that will upload to webserver and at the meantime will insert into database as url referencesvalue for @chapterid will get from drop down list(ddlLesson) and the index value will store in database.
now i am able to upload my images with the file name that i have given to web server, but I am unable to insert data to my database.
 Sub DoUpload(ByVal Sender As Object, ByVal e As System.EventArgs)        Dim sPath As String        Dim sFile As String        Dim sFullPath As String        Dim sSplit() As String        Dim sPathFriendly As String
              'Upload to same path as script. Internet Anonymous User must have write permissions        sPath = Server.MapPath("../Tutorial")        'sPath = Server.MapPath(".")        If Right(sPath, 1) <> "" Then            sPathFriendly = sPath 'Friendly path name for display            sPath = sPath & ""        Else            sPathFriendly = Left(sPath, Len(sPath) - 1)        End If
        'Save as same file name being posted        'The code below resolves the file name        '(removes path info)        sFile = txtFileName.Text        'sFile = txtUpload.PostedFile.FileName        sSplit = Split(sFile, "")        sFile = sSplit(UBound(sSplit))
        sFullPath = sPath & sFile        Try            txtUpload.PostedFile.SaveAs(sFullPath)            lblResults.Text = "<br>Upload of File " & sFile & " to " & sPathFriendly & " succeeded"
        Catch Ex As Exception
            lblResults.Text = "<br>Upload of File " & sFile & " to " & sPathFriendly & " failed for the following reason: " & Ex.Message        Finally            lblResults.Font.Bold = True            lblResults.Visible = True        End Try
        Dim mycommand As SqlCommand        Dim myConnection As SqlConnection        Message.InnerHtml = ""        'to all the valur to database        If IsValid Then
            myConnection = New SqlConnection("Server=localhost;UID=sa;pwd=;database=u")            mycommand = New SqlCommand("INSERT INTO t_linkTitle(link_chapterid,link_name,link_url) VALUES (@chapterid,@titleName,@titleUrl)", myConnection)
            mycommand.Parameters.Add("@chapterid", SqlDbType.VarChar, 50).Value = ddlLesson.SelectedItem.Value            mycommand.Parameters.Add("@titleName", SqlDbType.VarChar, 50).Value = txtAddTitle.Text            mycommand.Parameters.Add("@titleUrl", SqlDbType.VarChar, 100).Value = txtFileName.Text
            mycommand.Connection.Open()            msgErrorTitle.Style("color") = "OrangeRed"            Try                mycommand.ExecuteNonQuery()                msgErrorTitle.InnerHtml = "New title <b>" + txtAddTitle.Text + "</b> Added to " + "<b>" + ddlLesson.SelectedItem.Text + "</b><br>" + mycommand.ToString()            Catch Exp As SqlException
                If Exp.Number = 2627 Then                    msgErrorTitle.InnerHtml = "ERROR: Title already exists. Please use another title"                Else                    msgErrorTitle.InnerHtml = "ERROR: Could not add record, please ensure the fields are correctly filled out"                End If
            End Try
            mycommand.Connection.Close()        End If
        LoadTitle()
    End Sub

View 2 Replies View Related

Upload Image To SQL Database

Apr 3, 2006

I am creating a update, delete, edit form for my web database.  The form works in everyway except that when I try to upload the image to the database it does not go into the database.  (I know the pros and cons of storing images in a database.  In this instance it is what makes the most since. )
I have to admit I have never uploaded anything to my server or database before (other than plain text). I have read through several articles and have a high level of understanding.
I found an example on a website that used the OnInserting/OnUpdating command. But it is not working.  I tried to find another similar example so that I could better understand it and try to fix what must be wrong.  I can't find a similar example.
I am posting the code I have below. Any help would be most appreciated.
 
C# Code Behind
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
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 html_Test_Default3 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DetailsView1_ItemUpdated(Object sender, System.Web.UI.WebControls.DetailsViewUpdatedEventArgs e)
{
Response.Redirect("GridViewMasterDetailsInsertPage_cs.aspx");
}
protected void DetailsView1_ModeChanging(Object sender, System.Web.UI.WebControls.DetailsViewModeEventArgs e)
{
if (e.CancelingEdit == true)
{
Response.Redirect("GridViewMasterDetailsInsertPage_cs.aspx");
}

}
protected void SqlDataSource3_Inserting(object sender, SqlDataSourceCommandEventArgs e)
{
FileUpload stateTextBox = (FileUpload)DetailsView1.Rows[2].Cells[0].Controls[1];
System.IO.Stream inputStream = stateTextBox.PostedFile.InputStream;
int imageLength = stateTextBox.PostedFile.ContentLength;
byte[] imageBinary = new byte[imageLength];
int inputRead = inputStream.Read(imageBinary, 0, imageLength);
byte[] imageData = imageBinary;
System.Data.SqlClient.SqlParameter uploadData = new System.Data.SqlClient.SqlParameter("@photo", System.Data.SqlDbType.Image);
uploadData.Value = imageData;
e.Command.Parameters.Add(uploadData);
}
protected void New_Click(object sender, EventArgs e)
{
DetailsView1.ChangeMode(DetailsViewMode.Insert);
}
 
 
}
*************************************ASPX page
<%@ Page Language="C#" MasterPageFile="~/MasterPages/MasterPage.master" AutoEventWireup="true" CodeFile="DetailsViewEdit_cs.aspx.cs" Inherits="html_Test_Default3" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<form id="form1" runat="server" method="post" enctype="multipart/form-data">
<asp:DetailsView DefaultMode="Edit" AutoGenerateRows="False" DataKeyNames="recID"
DataSourceID="SqlDataSource3" HeaderText="Edit Articles" ID="DetailsView1" runat="server"
Width="275px" OnItemUpdated="DetailsView1_ItemUpdated" OnModeChanging="DetailsView1_ModeChanging">
<Fields>
<asp:BoundField DataField="recID" HeaderText="Record Number" SortExpression="recID" ReadOnly="True" />
<asp:TemplateField SortExpression="LiveAccess" HeaderText="LiveAccess" >
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource3" DataTextField="LiveAccess" DataValueField="LiveAccess" SelectedValue='<%# Bind("LiveAccess") %>'>
<asp:ListItem Text="Yes" Value="Yes" />
<asp:ListItem Text="No" Value="No" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="DevelopmentAccess" HeaderText="DevelopmentAccess" >
<EditItemTemplate>
<asp:DropDownList ID="DropDownList2" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource3" DataTextField="DevelopmentAccess" DataValueField="DevelopmentAccess" SelectedValue='<%# Bind("DevelopmentAccess") %>'>
<asp:ListItem Text="Yes" Value="Yes" />
<asp:ListItem Text="No" Value="No" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="MediaAccess" HeaderText="MediaAccess" >
<EditItemTemplate>
<asp:DropDownList ID="DropDownList3" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource3" DataTextField="MediaAccess" DataValueField="MediaAccess" SelectedValue='<%# Bind("MediaAccess") %>'>
<asp:ListItem Text="Yes" Value="Yes" />
<asp:ListItem Text="No" Value="No" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="DoctorAccess" HeaderText="DoctorAccess" >
<EditItemTemplate>
<asp:DropDownList ID="DropDownList4" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource3" DataTextField="DoctorAccess" DataValueField="DoctorAccess" SelectedValue='<%# Bind("DoctorAccess") %>'>
<asp:ListItem Text="Yes" Value="Yes" />
<asp:ListItem Text="No" Value="No" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField SortExpression="DealerAccess" HeaderText="DealerAccess" >
<EditItemTemplate>
<asp:DropDownList ID="DropDownList5" AppendDataBoundItems="true" runat="server" DataSourceID="SqlDataSource3" DataTextField="DealerAccess" DataValueField="DealerAccess" SelectedValue='<%# Bind("DealerAccess") %>'>
<asp:ListItem Text="Yes" Value="Yes" />
<asp:ListItem Text="No" Value="No" />
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ContentType" HeaderText="ContentType" SortExpression="ContentType" />
<asp:BoundField DataField="ProductType" HeaderText="ProductType" SortExpression="ProductType" />

<asp:BoundField DataField="ReviewDate" HeaderText="ReviewDate" SortExpression="ReviewDate" />
<asp:BoundField DataField="ReleaseDate" HeaderText="ReleaseDate" SortExpression="ReleaseDate" />
<asp:BoundField DataField="ObsoleteDate" HeaderText="ObsoleteDate" SortExpression="ObsoleteDate" />
<asp:TemplateField HeaderText="Title">
<EditItemTemplate>
<asp:TextBox id="EditTitle" Text='<%# Bind("Title") %>' Runat="Server"
TextMode="SingleLine" Rows="1" Width="400px" Font-Size="9pt"/>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Sub Title">
<EditItemTemplate>
<asp:TextBox id="EditSubtitle" Text='<%# Bind("Subtitle") %>' Runat="Server"
TextMode="SingleLine" Rows="1" Width="400px" Font-Size="9pt"/>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Copy">
<EditItemTemplate>
<asp:TextBox id="EditCopy" Text='<%# Bind("Copy") %>' Runat="Server"
TextMode="MultiLine" Rows="5" Width="400px" Font-Size="9pt"/>
</EditItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Keywords">
<EditItemTemplate>
<asp:TextBox id="Keywords" Text='<%# Bind("Keywords") %>' Runat="Server"
TextMode="MultiLine" Rows="5" Width="400px" Font-Size="9pt"/>
</EditItemTemplate>
</asp:TemplateField>

<asp:ImageField DataImageUrlField="Picture"></asp:ImageField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:FileUpload ID="FileUpload1" FileName='<%# Bind("Picture") %>' runat="server" />
<asp:RequiredFieldValidator ID="FileUploadValidator" ControlToValidate="FileUpload1" runat="Server">*</asp:RequiredFieldValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Notes">
<EditItemTemplate>
<asp:TextBox id="EditNotes" Text='<%# Bind("Notes") %>' Runat="Server"
TextMode="MultiLine" Rows="5" Width="400px" Font-Size="9pt"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="WriterName" HeaderText="WriterName" SortExpression="WriterName" />
<asp:BoundField DataField="WriterEmailAddress" HeaderText="WriterEmailAddress" SortExpression="WriterEmailAddress" />
<asp:BoundField DataField="Language" HeaderText="Language" SortExpression="Language" />
<asp:CommandField ShowEditButton="True" />
</Fields>
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:myConnection %>"
SelectCommand="SELECT [recID], [Date], [LiveAccess], [DevelopmentAccess], [MediaAccess], [DoctorAccess], [DealerAccess], [ContentType], [ProductType], [Title], [Subtitle], [ReviewDate], [ReleaseDate], [ObsoleteDate], [Keywords], [Picture], [Copy], [Notes], [WriterName], [WriterEmailAddress], [Language] FROM [Articles] WHERE ([recID] = @recID)"
UpdateCommand="UPDATE [Articles] SET [LiveAccess]=@LiveAccess, [DevelopmentAccess]=@DevelopmentAccess, [MediaAccess]=@MediaAccess, [DoctorAccess]=@DoctorAccess, [DealerAccess]=@DealerAccess, [ContentType]=@ContentType, [ProductType]=@ProductType, [Title]=@Title, [Subtitle]=@Subtitle, [ReviewDate]=@ReviewDate, [ReleaseDate]=@ReleaseDate, [ObsoleteDate]=@ObsoleteDate, [Keywords]=@Keywords, [Picture]=@Picture, [Copy]=@Copy, [Notes]=@Notes, [WriterName]=@WriterName, [WriterEmailAddress]=@WriterEmailAddress, [Language]=@Language WHERE [recID] = @recID"
OnUpdating="SqlDataSource3_Inserting">
<SelectParameters>
<asp:QueryStringParameter Name="recID" QueryStringField="ID" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="LiveAccess" Type="String"/>
<asp:Parameter Name="DevelopmentAccess" Type="String" />
<asp:Parameter Name="MediaAccess" Type="String" />
<asp:Parameter Name="DoctorAccess" Type="String" />
<asp:Parameter Name="DealerAccess" Type="String" />
<asp:Parameter Name="ContentType" Type="String" />
<asp:Parameter Name="ProductType" Type="String" />
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="Subtitle" Type="String" />
<asp:Parameter Name="ReviewDate" Type="String" />
<asp:Parameter Name="ReleaseDate" Type="String" />
<asp:Parameter Name="ObsoleteDate" Type="String" />
<asp:Parameter Name="Keywords" Type="String" />
<asp:Parameter Name="Copy" Type="String" />
<asp:Parameter Name="Notes" Type="String" />
<asp:Parameter Name="WriterName" Type="String" />
<asp:Parameter Name="WriterEmailAddress" Type="String" />
<asp:Parameter Name="Language" Type="String" />
</UpdateParameters>
</asp:SqlDataSource>
</form>
</asp:Content>

View 1 Replies View Related

Sql Image Upload And Retrieval?

Apr 9, 2006

Hi all, I dont know if anyone here can help me...I am using ASP.NEt with VB.Net and SQL Sever...What I am trying to do is create a system whereby it allows users to upload images into sql server, and thereon later retireve this image.I used a book called The Ultimate VB.Net and ASP.Net Code Book, and it basically gave me the code below to upload and retrieve images.  I seem to have managed to allow the uploading of images, with them being stored as <byte> in my database, thought I have no idea how to retrieve them...Does anyone have any ideas???Here is the code I followed.. :"Storing Uploaded Files in Your Database First, a few tips on storing files inside your SQL Server database.For convenience, you’ll really need to store at least three bits of information about your file to get it out in the same shape as you put it in. I’d suggest “dataâ€? (a field that will hold your actual file as a byte array, data type “imageâ€?), “typeâ€? (a field to hold details of the type of file it is, data type “varcharâ€?), and “lengthâ€? (a field to hold the length in bytes of your file, data type “intâ€?). I’d also recommend “downloadNameâ€?, a field to hold the name that the file had when it was uploaded, data type “varcharâ€?. This helps suggest a name should the file be downloaded again via the Web.The problem you have is translating the information from the File Field control into an acceptable format for your database. For a start, you need to get your file into a byte array to store it in an image field. You also need to extract the file type, length, and the download name. Once you have this, set your fields to these values using regular ADO.NET code.So, how do you get this information? It’s simple: just use the following ready-to-run code snippets, passing in your File Field control as an argument. Each function will return just the information you want to feed straight into your database, from a byte array for the image field to a string for the file type.Public Function GetByteArrayFromFileField( _     ByVal FileField As System.Web.UI.HtmlControls.HtmlInputFile) _     As Byte()     ' Returns a byte array from the passed     ' file field controls file     Dim intFileLength As Integer, bytData() As Byte     Dim objStream As System.IO.Stream     If FileFieldSelected(FileField) Then         intFileLength = FileField.PostedFile.ContentLength         ReDim bytData(intFileLength)         objStream = FileField.PostedFile.InputStream         objStream.Read(bytData, 0, intFileLength)         Return bytData     End If End Function Public Function FileFieldType(ByVal FileField As _   System.Web.UI.HtmlControls.HtmlInputFile) As String     ' Returns the type of the posted file     If Not FileField.PostedFile Is Nothing Then _       Return FileField.PostedFile.ContentType End Function Public Function FileFieldLength(ByVal FileField As _   System.Web.UI.HtmlControls.HtmlInputFile) As Integer     ' Returns the length of the posted file     If Not FileField.PostedFile Is Nothing Then _       Return FileField.PostedFile.ContentLength End Function Public Function FileFieldFilename(ByVal FileField As _   System.Web.UI.HtmlControls.HtmlInputFile) As String     ' Returns the core filename of the posted file     If Not FileField.PostedFile Is Nothing Then _       Return Replace(FileField.PostedFile.FileName, _       StrReverse(Mid(StrReverse(FileField.PostedFile.FileName), _       InStr(1, StrReverse(FileField.PostedFile.FileName), ""))), "") End Function Sorted! One question remains, however. Once you’ve got a file inside a database, how do you serve it back up to a user? First, get the data back out of SQL Server using regular ADO.NET code. After that? Well, here’s a handy function that’ll do all the hard work for you. Simply pass the data from your table fields and hey presto:Public Sub DeliverFile(ByVal Page As System.Web.UI.Page, _   ByVal Data() As Byte, ByVal Type As String, _   ByVal Length As Integer, _   Optional ByVal DownloadFileName As String = "")     ' Delivers a file, such as an image or PDF file,     ' back through the Response object     ' Sample usage from within an ASP.NET page:     ' - DeliverFile(Me, bytFile(), strType, intLength, "MyImage.bmp")     With Page.Response         .Clear()         .ContentType = Type         If DownloadFileName <> "" Then             Page.Response.AddHeader("content-disposition", _               "filename=" & DownloadFileName)         End If         .OutputStream.Write(Data, 0, Length)         .End()     End With End Sub Simply pass your byte array, file type, and length, and it’ll send it straight down to your surfer. If it’s an image, it’ll be displayed in the browser window. If it’s a regular file, you’ll be prompted for download.If it’s made available for download, this function also allows you to specify a suggested download file name, a technique that many ASP.NET developers spend weeks trying to figure out. Easy! Working with Uploaded Images Whether you’re building the simplest of photo album Web sites or a fully fledged content management system, the ability to work with uploaded images is a vital one, and with ASP.NET, it’s a real doddle.The following code snippet shows you how, by example. It takes a data stream from the File Field control and converts it into an image object, adding simple error handling should the uploaded file not actually be an image. The code then uses this image object to extract a few core details about the file, from its dimensions to file type:' Get data into image format Dim objStream As System.IO.Stream = _   MyFileField.PostedFile.InputStream Dim objImage As System.Drawing.Image Try     ' Get the image stream     objImage = System.Drawing.Image.FromStream(objStream) Catch     ' This is not an image, exit the method (presuming code is in one!)     Exit Sub End Try ' Filename Dim strOriginalFilename As String = MyFileField.PostedFile.FileName ' Type of image Dim strImageType If objImage.RawFormat.Equals(objImage.RawFormat.Gif) Then     strImageType = "This is a GIF image" ElseIf objImage.RawFormat.Equals(objImage.RawFormat.Bmp) Then     strImageType = "This is a Bitmap image" ElseIf objImage.RawFormat.Equals(objImage.RawFormat.Jpeg) Then     strImageType = "This is a JPEG image" ElseIf objImage.RawFormat.Equals(objImage.RawFormat.Icon) Then     strImageType = "This is an icon file" ElseIf objImage.RawFormat.Equals(objImage.RawFormat.Tiff) Then     strImageType = "This is a TIFF file" Else     strImageType = "Other"   End If   ' Dimensions   Dim strDimensions As String   strDimensions = "Width in pixels: " & objImage.Width & _     ", Height in pixels: " & objImage.Height   ' Send raw output to browser   Response.Clear()   Response.Write(strOriginalFilename & "<p>" & strImageType & _     "<p>" & strDimensions)   Response.End() "For some reason the retrieval code isnt working for me..Can anyone provide any help? even if it means using another method?

View 1 Replies View Related

Upload File To A DB In Binary

Apr 20, 2006

Hi have done the following but get the errors at the end, any ideas
 Created a stored procedureALTER PROCEDURE ulfile@upload varchar(200)ASINSERT INTO results(@upload)VALUES (@Upload)RETURN after sitting for two hours I realised I had a comma after (200) then the following in the .cs file using System;using System.Data;using System.Configuration;using System.Collections;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 Default3 : System.Web.UI.Page{//PostedFile Property of Type HTTPPostedFileint intDocLen = txtFileContents.PostedFile.ContentLength;byte[] Docbuffer = new byte[intDoclen];protected void Page_Load(object sender, EventArgs e){ Stream objStream;//InputStream://Gets a Stream object which points to an uploaded Document; //to prepare for reading the contents of the file.objStream = txtFileContents.PostedFile.InputStream;objStream.Read(Docbuffer, 0, intDocLen);//results is the connection objectcmdUploadDoc = new SqlCommand("ulfile", results);cmdUploadDoc.CommandType = CommandType.StoredProcedure;//Add the Params which in the Stored Proc cmdUploadDoc.Parameters.Add("@upload ", SqlDbType.VarChar, 200);//Set Params ValuescmdUploadDoc.Parameters[0].Value = txtTitle.Text;//Set the "@Doc" Param to be Docbuffer byet ArraycmdUploadDoc.Parameters[1].Value = Docbuffer;cmdUploadDoc.Parameters[2].Value = strDocType; }private void btnSubmit_Click(object sender, System.EventArgs e){string strDocExt;//strDocType to store Document type which will be Stored in the Databasestring strDocType;//Will be used to determine Document lengthint intDocLen;//Stream object used for reading the contents of the Uploading DocumnetStream objStream;SqlConnection results;SqlCommand cmdUploadDoc;if(IsValid){if(txtFileContents.PostedFile != null){//Determine File TypestrDocExt = CString.Right(txtFileContents.PostedFile.FileName,4).ToLower();switch(strDocExt){case ".doc":strDocType = "doc";break;case ".ppt":strDocType = "ppt";break;case ".htm":strDocType = "htm";break;case ".html":strDocType = "htm";break;case ".jpg":strDocType = "jpg";break;case ".gif":strDocType = "gif";break;case ".im":strDocType = "im";break;default:strDocType = "txt";break;}//Grab the Content of the Uploaded DocumentintDocLen = txtFileContents.PostedFile.ContentLength;//buffer to hold Document Contentsbyte[] Docbuffer = new byte[intDocLen];//InputStream://Gets a Stream object which points to an uploaded Document; //to prepare for reading the contents of the file.objStream = txtFileContents.PostedFile.InputStream;//Store the Content of the Documnet in a buffer//This buffer will be stored in the DatabaseobjStream.Read(Docbuffer ,0,intDocLen);//Add Uploaded Documnet to Database as Binary//You have to change the connection stringBooksConn = new SqlConnection("Server=66.179.84.110;UID=******;PWD=******;Database=******");//Setting the SqlCommandcmdUploadDoc = new SqlCommand("ulfile",results);cmdUploadDoc.CommandType = CommandType.StoredProcedure;cmdUploadDoc.Parameters.Add("@upload ",SqlDbType.VarChar,200);cmdUploadDoc.Parameters[0].Value = txtTitle.Text;cmdUploadDoc.Parameters[1].Value = Docbuffer ;cmdUploadDoc.Parameters[2].Value = strDocType;Results.Open();cmdUploadDoc.ExecuteNonQuery();Results.Close();}//End of if(txtFileContents.PostedFile != null)}//End Of if(IsValid)}//End of Method btnSubmit_Click}  And the form code <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %><!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>Untitled Page</title></head><body><form id="frmUpload" method="post" enctype="multipart/form-data" runat="server"><span>Title</span><asp:textbox id="txtTitle" runat="server" EnableViewState="False"></asp:textbox><asp:requiredfieldvalidator id="valrTitle" runat="server" ErrorMessage="* Required" ControlToValidate="txtTitle">* Required</asp:requiredfieldvalidator><span>Document to Upload</span><input id="txtFileContents" type="file" runat="server" name="txtFileContents"></></><asp:button id="btnSubmit" Text="Submit" Runat="server" OnClick="btnSubmit_Click"></asp:button>   </form></body></html>  however when I try and view in browser I get the following Line 21:
Line 22:
Line 23: Stream objStream;
Line 24: //InputStream:
Line 25: //Gets a Stream object which points to an uploaded Document;  I have trawlled the net, MSDN and anywhere else I can find to see what it is and nothing. eventually changed  Stream.objstream to System.IO.Stream objStream; And now getting the following error Line 29:
Line 30: //results is the connection object
Line 31: cmdUploadDoc = new SqlCommand("ulfile",results);
Line 32: cmdUploadDoc.CommandType = CommandType.StoredProcedure;
Line 33: //Add the Params which in the Stored Proc  Can anyone help?

View 2 Replies View Related







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