I have a site that I've almost completed and while testing it today noticed that it's not uploading any files or doing the bulk insert in SQL that I need it to. Here is my codebehind: - Imports System.IO
-
Imports System.Data
-
Imports System.Data.SqlClient
-
Partial Class _Default
-
Inherits System.Web.UI.Page
-
Protected Sub Submit1_Click(ByVal sender As Object, ByVal e As EventArgs)
-
-
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
-
Dim fn As String = System.IO.Path.GetFileName(File1.PostedFile.FileName)
-
Dim SaveLocation As String = Server.MapPath("Data") & "\" & fn
-
Try
-
File1.PostedFile.SaveAs(SaveLocation)
-
Response.Write(<center>Thank you for your submission.</center>)
-
-
' get the file that was submitted and check if it was .txt file
-
Dim theFile As FileInfo = New FileInfo(SaveLocation)
-
If theFile.Extension <> ".txt" Then
-
Response.Write(<center>Please submit a text file.</center>)
-
End If
-
-
Dim importPath As String = Server.MapPath("Data") & "\upload.txt"
-
If File.Exists(importPath) Then
-
' do something with existing upload.txt file, maybe archive?
-
End If
-
-
' rename the uploaded file to upload.txt for importing
-
theFile.MoveTo(importPath)
-
-
' and bulk import the data:
-
Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
-
Dim results As New DataTable
-
-
Using con As New SqlConnection(connection)
-
con.Open()
-
-
' execute the bulk import
-
Using cmd As SqlCommand = con.CreateCommand
-
cmd.CommandText = "bulk insert dialerresults from '" & importPath & "' " & _
-
" with ( fieldterminator = ',', rowterminator = '\n' )"
-
cmd.ExecuteNonQuery()
-
End Using
-
End Using
-
-
Catch Exc As Exception
-
Response.Write("Error: " & Exc.Message)
-
End Try
-
Else
-
Response.Write(<center>Please select a file to upload.</center>)
-
End If
-
-
End Sub
-
End Class
Can anyone see why the file is not being uploaded? I'm sure its something simple but I've been working on this for a while and may have missed something. Any assistance would be welcome.
Thank you,
Doug
54 4153
First thing that comes to mind is that you've placed your File1 in an UpdatePanel.
UpdatePanels do not support the upload of files...the files will simply not get to the server.
-Frinny
Frinny,
I'm sorry but I'm new to asp.net and know nothing of UpdatePanels. What would be a good workaround for this issue?
Thank you,
Doug
Well if you don't know what an UpdatePanel is then it's very unlikely that you are using it. So just ignore my previous point.
To be quite honest, after skimming through your code right now, I'm not sure that your posted code would even compile. Line 18 is going to cause you problems.
Have you tried stepping through the application and watching what happens to see if you can figure out what's going on?
-Frinny
You should probably check out this MSDN documentation on the FileUpload control. It has a working example that you could probably use to get you started.
-Frinny
Frinny,
This code is comprised of code I've written and something that someone else wrote. The code does compile and I have tried loading two different files (one a .txt file and one a .pdf file) and neither would show up in the destination folder. I've built the page, and debugged it with no errors. When I tried to upload the .pdf page, what should have happened, was that I should have received an error that that files of that format were not accepted and I didn't get that message either. Any ideas as to what may be causing that? Would those be symptoms of a UpdatePanel issue?
If you had put your FileUpload control into an UpdatePanel then the FileUpload control's PostedFile will always be nothing.
If you have done this, take the FileUpload control out of the UpdatePanel.
Frinny,
Can you point out to me where the UpdatePanel is in my code? I'll gladly take the lines of code out once I can identify them.
You would have to post the ASPX page "code" (look at the page and click "source" view button).
I can't tell unless you post that code.
- <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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 runat="server">
-
<title>Upload Page</title>
-
<style type="text/css">
-
#form1
-
{
-
height: 128px;
-
}
-
#File1
-
{
-
top: 66px;
-
}
-
#Submit1
-
{
-
top: 103px;
-
left: 591px;
-
}
-
#TextArea1
-
{
-
z-index: 1;
-
left: 303px;
-
top: 45px;
-
position: absolute;
-
}
-
</style>
-
<script language="javascript" type="text/javascript">
-
// <!CDATA[
-
-
function Submit1_onclick() {
-
-
}
-
-
// ]]>
-
</script>
-
</head>
-
<body>
-
<form id="form1" enctype="multipart/form-data" runat="server">
-
<br />
-
-
<br />
-
<input type="File" id="File1" name="File1" runat="server"
-
style="position: absolute; left: 512px;" />
-
<br />
-
<input type="Submit" id="Submit1" value="Upload" runat="server"
-
style="position: absolute; height: 30px;"
-
onclick="return Submit1_onclick()" />
-
</form>
-
</body>
-
</html>
-
Frinny, there is my code for the page. As you can see, there's not much too it. I know that it's not really clean but I'll worry about cleaning it up later. Right now I'm just trying to get the "mechanics" of this working.
Thank you for taking a look at it,
Doug
Oh....
Well you aren't using an UpdatePanel ;)
But you are using an HTML input element.
You should be using the ASP.NET FileUpload control control instead!!
Oh wait there's another thing
You may not even be reaching the code that you have posted because you don't have an asp.net Button on the page either!
Change your submit HTML button into an ASP.NET button as well.
Like this: -
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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 runat="server">
-
<title>Upload Page</title>
-
<style type="text/css">
-
#form1
-
{
-
height: 128px;
-
}
-
#File1
-
{
-
top: 66px;
-
}
-
#Submit1
-
{
-
top: 103px;
-
left: 591px;
-
}
-
#TextArea1
-
{
-
z-index: 1;
-
left: 303px;
-
top: 45px;
-
position: absolute;
-
}
-
</style>
-
-
</head>
-
<body>
-
<form id="form1" enctype="multipart/form-data" runat="server">
-
<br />
-
-
<br />
-
<asp:FileUpload ID="File1" runat="server"
-
style="position: absolute; left: 512px;" />
-
<br />
-
<asp:Button id="Submit1" runat="server"
-
style="position: absolute; height: 30px;"
-
onclick="Submit1_Click" />
-
</body>
-
</html>
Frinny,
So if I change the html button to an asp.net button will it automatically rewrite the codebehind to reflect the upload controls in Visual Studio?
I'm not sure.
The C# IDE is different the the VB.NET IDE and I work with VB.NET most of the time.
But typically what happens is that when you change your HTML code into an ASP.NET control, that control is "registered" into the .designer.cs file so that it is accessable to work in both the ASPX code and your C# code.
ASP.NET controls have 2 aspects to them: client side and server side. In fact when your application has finished executing the server-side code it Renders the page's output which is sent to the browser. The only thing the browser understands is HTML (as you already know). So when the server-side code finishes executing it turns all of the ASP.NET controls into HTML.
The important thing is that the HTML is generated and maintained by ASP.NET
This means that if the user clicks an ASP.NET button on the page, you can handle the buttons Click Event in your C# server code.
If you use just regular HTML for the button then there is no Click Event generated because ASP.NET isn't in control of it.
So it's important that you use ASP.NET controls when developing ASP.NET applications/websites :)
Anyways,
You declare your button in the ASPX code as I have shown you...This will give you access events and properties (and a lot more) for the button in your C# code that you never had before.
Frinny,
So I changed the button to an asp.net button and now when I attempt to upload a file, I get the following on my page:
Thank you for your submission.
Error: Cannot create a file when that file already exists.
Thank you for your submission.
Error: Cannot create a file when that file already exists.
That was when I try to upload a .txt file, when I try to upload anything but that this is what I get:
Thank you for your submission.
Please submit a text file.
Error: Cannot create a file when that file already exists.
Thank you for your submission.
Please submit a text file.
Error: Cannot create a file when that file already exists.
So it's duplicating the error text and it's not aligning them to center as they should be. I realize that I should put a label to output the errors too but as I said, right now I just want to get the mechanics to work the way that they should. Any idea why it would duplicate the error responses?
Well I kind of knew that was your next question.
You should never use Response.Write in your C# code.
If you do then the content that you're writing to the page will be placed somewhere invalid....mainly it's placed above the <html> element...which is clearly invalid
What I recommend is that you add an ASP.NET Label control to the page in the place where you want the error message to appear.
When you encounter an error set this Label's Text property to the text that you want to display.
The center tag has been obsolete for a very long time anyways.
You should use CSS instead ;)
-Frinny
Frinny,
Could that also be the reason why the file is not being uploaded?
?? I thought the file is being uploaded ??
My apologies, yes in fact the file is being uploaded. I have tried to take the response.write element out and absolute position a label. The reason I wanted to do that is to drap and drop the response write label to beneath the upload button but found that I can't do that. How is the best way to accomplish positioning the label beneath the upload button without completely re-writing my page?
Also,. the file is being uploaded but the sql bulk insert isn't working. The error message I got is this:
Thank you for your submission.Error: Object reference not set to an instance of an object.Thank you for your submission.Error: Cannot create a file when that file already exists.
First we'll address why you can't get your label in the correct spot.
Could you post your aspx code again?
- <%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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 runat="server">
-
<title>Upload Page</title>
-
<style type="text/css">
-
#form1
-
{
-
height: 189px;
-
width: 919px;
-
}
-
#File1
-
{
-
top: 66px;
-
}
-
#Submit1
-
{
-
top: 103px;
-
left: 591px;
-
}
-
#TextArea1
-
{
-
z-index: 1;
-
left: 303px;
-
top: 45px;
-
position: absolute;
-
}
-
</style>
-
<script language="javascript" type="text/javascript">
-
// <!CDATA[
-
-
function Submit1_onclick() {
-
-
}
-
-
// ]]>
-
</script>
-
</head>
-
<body>
-
<form id="form1" enctype="multipart/form-data" runat="server">
-
<br />
-
-
<br />
-
<asp:FileUpload ID="File1" runat="server"
-
style="position: absolute; left: 512px;" />
-
<br />
-
<asp:Button id="Submit1" runat="server"
-
style="position: absolute; height: 30px; top: 101px; left: 572px;"
-
onclick="Submit1_Click" Text="Upload" />
-
</form>
-
</body>
-
</html>
-
I don't see a Label at all on your page.
If you want it to appear right under the button then place on there: -
<body>
-
<form id="form1" enctype="multipart/form-data" runat="server">
-
<br />
-
-
<br />
-
<asp:FileUpload ID="File1" runat="server"
-
style="position: absolute; left: 512px;" />
-
<br />
-
<asp:Button id="Submit1" runat="server"
-
style="position: absolute; height: 30px; top: 101px; left: 572px;"
-
onclick="Submit1_Click" Text="Upload" />
-
<br />
-
<asp:Label id="message" runat="server"></asp:Label>
-
-
</form>
-
</body>
-
</html>
But when I show that in design mode, the label is on the far left hand side of the screen and not beneath the upload button. Secondly, with that, how do I get the error message to show there? I'm assuming at that point that I'm doing some sort of validator. What would be the best validation to use for that? Custom or RegularExpression?
It's simple html/css stuff here.
I'm sorry I didn't realize your button was absolutely positioned (seems a bit odd to me)....I think you even mentioned it before.
Since the upload control, the button and the error message (the message label) belong to the same grouping they should be placed in the same block. You could either place them into a div element or you could place them into an asp.net Panel element (which renders as a div). I'd choose the panel element personally because it's assigned a unique ID by ASP.NET and you may want to be able to access it in your C# code.
You can set the style of a Panel the same way as you would set the style of a div. The only difference is that if you have a CSS class that you want to use for the Panel you would set the CssClass property (whereas you'd just set the class property of the div element).
So, the following should work for you: -
<body>
-
<form id="form1" enctype="multipart/form-data" runat="server">
-
<asp:Panel ID="UploadControlsSection" runat="server" style="position: absolute; left: 512px;">
-
<asp:FileUpload ID="File1" runat="server" />
-
<br />
-
<asp:Button id="Submit1" runat="server"
-
style="height: 30px; margn-left:60px;"
-
onclick="Submit1_Click" Text="Upload" />
-
<br />
-
<asp:Label id="message" runat="server"></asp:Label>
-
</asp:Panel>
-
</form>
-
</body>
-
</html>
All of your validation is currently being done server side (in your C# code).
If you encounter an error you should set the message.Text = "error message" to display a message to the user.
You aren't using any custom validators (which run client side) or anything of the sort at this point.
I have a feeling that you are trying to do too many things at once.
First get this working...get your fie to upload, do your validation server side, get your sql update to work.
Then you can think about adding custom client side validation to your page.
-Frinny
Ok so the file is being uploaded but now I've noticed that there are two files that are being put in the data folder. One is whatever the document is called (in my case it was called test) and also the file that is being renamed. There should only be one file in the directory called "upload.txt." Secondly, I don't think that the SQL bulk insert command (at least from the code side) is working at all.
dougancil:
There should only be one file in the directory called "upload.txt."
This doesn't make sense.
Say you have 2 users using the website at the same time and both users upload a file to the server at the same time...in this case one of the user's files will be over written with the other user's files.
Each user should be able to create a file of their own to avoid this problem. dougancil:
Secondly, I don't think that the SQL bulk insert command (at least from the code side) is working at all.
Are you seeing the same error message as before?
-Frinny
Frinny,
The way that this is going to be organized is that one user per client will have access to upload pages to this server. They will be divided out by directories on the server so in theory, there should never be 2 users on this page from the same client at the same time trying to upload files.
Secondly, I am seeing this as an error:
Thank you for your submission.Error: Object reference not set to an instance of an object.Thank you for your submission.Error: Cannot create a file when that file already exists.
I can verify that there are two files in the remote directory (the "Data" directory) and the file is a comma delimited file which has been tested and will upload to the sql server with the command that I have in the codebehind.
Could you please post your C# code so that I can see what you have?
Basically you're getting an error message stating that you cannot create a file with the same name...you should either overwrite the file or delete it and recreate when you save the file to the server.
You are also getting an "Object reference not set to an instance of an object" error which means you are trying to access something that doesn't exist yet (an object that hasn't been instantiated yet).
If you could point out which lines these errors are occurring on when you post your C# code that would be very helpful.
Frinny,
This is .vb code not .cs but here's the code. Also, the error I'm getting is when I press the upload button. It's not giving me a line number for the error. - Imports System.IO
-
Imports System.Data
-
Imports System.Data.SqlClient
-
Partial Class _Default
-
Inherits System.Web.UI.Page
-
Protected Sub Submit1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Submit1.Click
-
-
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
-
Dim fn As String = System.IO.Path.GetFileName(File1.PostedFile.FileName)
-
Dim SaveLocation As String = Server.MapPath("Data") & "\" & fn
-
Try
-
File1.PostedFile.SaveAs(SaveLocation)
-
Response.Write("Thank you for your submission.")
-
-
' get the file that was submitted and check if it was .txt file
-
Dim theFile As FileInfo = New FileInfo(SaveLocation)
-
If theFile.Extension <> ".txt" Then
-
Response.Write("Please submit a text file.")
-
End If
-
-
Dim importPath As String = Server.MapPath("Data") & "\upload.txt"
-
If File.Exists(importPath) Then
-
' do something with existing upload.txt file, maybe archive?
-
End If
-
-
' rename the uploaded file to upload.txt for importing
-
theFile.MoveTo(importPath)
-
-
' and bulk import the data:
-
Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
-
Dim results As New DataTable
-
-
Using con As New SqlConnection(connection)
-
con.Open()
-
-
' execute the bulk import
-
Using cmd As SqlCommand = con.CreateCommand
-
cmd.CommandText = "bulk insert dialerresults from '" & importPath & "' " & _
-
" with ( fieldterminator = ',', rowterminator = '\n' )"
-
cmd.ExecuteNonQuery()
-
End Using
-
End Using
-
-
Catch Exc As Exception
-
Response.Write("Error: " & Exc.Message)
-
End Try
-
Else
-
Response.Write("Please select a file to upload.")
-
End If
-
-
End Sub
-
-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
-
-
End Sub
-
End Class
See the comments I've made in the code -
Imports System.IO
-
Imports System.Data
-
Imports System.Data.SqlClient
-
Partial Class _Default
-
Inherits System.Web.UI.Page
-
Protected Sub Submit1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Submit1.Click
-
-
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
-
Dim fn As String = System.IO.Path.GetFileName(File1.PostedFile.FileName)
-
'The following SaveLocation is going to upload a file with the name of the original file uploaded.
-
'I thought that you were supposed to be saving the file as "upload.txt"??
-
'I've changed this so that it suits your requirements.
-
' Dim SaveLocation As String = Server.MapPath("Data") & "\" & fn
-
Dim SaveLocation As String = Server.MapPath("Data") & "\upload.txt"
-
-
'At this point I would check to see if the file exists already
-
'If it does exist Delete the existing one so that the new one can be created
-
If IO.File.Exists(SaveLocation) Then
-
IO.File.Delete(SaveLocation)
-
End If
-
-
Try
-
File1.PostedFile.SaveAs(SaveLocation)
-
'Remember how I warned you Not to use Response.Write?
-
'I know I said don't use it in your C# code....
-
'but the same thing applies to VB.NET code.
-
'I've removed this line and I am setting the text of the Message Label instead
-
' Response.Write("Thank you for your submission.")
-
message.Text = "Thank you for your submission"
-
-
' get the file that was submitted and check if it was .txt file
-
Dim theFile As FileInfo = New FileInfo(SaveLocation)
-
If theFile.Extension <> ".txt" Then
-
'Again Response.Write is not good....Commenting it out
-
' Response.Write("Please submit a text file.")
-
'In the following line I'm replacing the message Label's Text with the error mssage
-
message.Text = "Please submit a text file."
-
End If
-
-
-
'What are you doing Here?
-
'I'm commenting this whole block of logic out because it doesn't make sense
-
' Dim importPath As String = Server.MapPath("Data") & "\upload.txt"
-
' If File.Exists(importPath) Then
-
' ' do something with existing upload.txt file, maybe archive?
-
' End If
-
'
-
' ' rename the uploaded file to upload.txt for importing
-
' theFile.MoveTo(importPath)
-
-
' and bulk import the data:
-
Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
-
Dim results As New DataTable
-
-
Using con As New SqlConnection(connection)
-
con.Open()
-
-
' execute the bulk import
-
Using cmd As SqlCommand = con.CreateCommand
-
'I changed the command text......
-
' cmd.CommandText = "bulk insert dialerresults from '" & importPath & "' " & _
-
' " with ( fieldterminator = ',', rowterminator = '\n' )"
-
-
cmd.CommandText = "bulk insert dialerresults from '" & SaveLocation & "' " & _
-
"with ( fieldterminator = ',', rowterminator = '\n' )"
-
-
cmd.ExecuteNonQuery()
-
End Using
-
End Using
-
-
Catch Exc As Exception
-
'Again Response.Write is not good....Commenting it out
-
' Response.Write("Error: " & Exc.Message)
-
'You are not seeing a line number that the problem is occurring on
-
'because you aren't displaying the StackTrace....
-
'In the following line I'm replacing the message Label's Text with the StackTrace of the exception
-
-
message.Text = Exc.StackTrace
-
-
End Try
-
Else
-
'Again Response.Write is not good....Commenting it out
-
' Response.Write("Please select a file to upload.")
-
'In the following line I'm replacing the message Label's Text with the error message
-
-
message.Text = "Please select a file to upload"
-
End If
-
-
End Sub
-
-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
-
-
End Sub
-
End Class
Frinny,
I've pasted your code and reloaded the web site. I get the following error:
at _Default.Submit1_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\Webfile1\Default.aspx.vb:line 52
What line is line 52 in the posted code?
here is line 52:
Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresu lts").ConnectionString
Well I'm not seeing any blue underline squiggles when I take that code and past it into a temporary testing page....
Are you seeing this displayed in your message label when you try to upload the file then?
What is the error message?
I am seeing what I posted in the message label beneath the upload button ... but it's showing when I load the page. So the error is there before I even "post" a file.
Here's my connection string in the web.config file:
<add name="Dialeresults" connectionString="server=10.1.1.40;database=dialer results;uid=xxx;password=xxxx;" providerName="System.Data.SqlClient" />
</connectionStrings>
Sorry here's the proper post:
<connectionStrings>
<add name="Dialeresults" connectionString="server=10.1.1.40;database=dialer results;uid=xxxx;password=xxxxxxx;" providerName="System.Data.SqlClient" />
</connectionStrings>
Do you have your connection string defined in your web.config file?
Is it defined with the key value you're using here?
This is probably where you're getting your "object not set to a reference" error.
If you can't see the message then change line 78 to:
message.Text =Exc.Message + " " + Exc.StackTrace
I changed line 78 and now get the following error:
Object reference not set to an instance of an object. at _Default.Submit1_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\Webfile1\Default.aspx.vb:line 52
Normally I don't create a test page to help people out but this time I did.
I copied the code we're working on into the test page and noticed a Lot of problems.
First of all you are uploading the file to the server before you are checking the file extension.
What if this file was a virus and all the end user wanted to do was get the virus to the server?
You can check to make sure the file extension is valid before saving it to the server!
In the code I'm posting now I've fixed this problem.
I've also broken the code up into 2 functions: one responsible for uploading the file....and the other is responsible for saving it to the database.
If the file does not upload...then I'm not calling the save-to-database function.
See below: -
Imports System.IO
-
Imports System.Data
-
Imports System.Data.SqlClient
-
Partial Class _Default
-
Inherits System.Web.UI.Page
-
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
-
-
End Sub
-
-
Private Sub Submit1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Submit1.Click
-
Dim SaveLocation As String = Server.MapPath("~/TempImages") & "\upload.txt"
-
If UploadFile(SaveLocation) Then
-
'the file was uploaded: now try saving it to the database
-
SaveToDatabase(SaveLocation)
-
End If
-
End Sub
-
-
Private Function UploadFile(ByVal SavePath As String) As Boolean
-
Dim fileWasUploaded As Boolean = False 'indicates whether or not the file was uploaded
-
-
'Checking if the file upload control contains a file
-
If Not File1.PostedFile Is Nothing And File1.PostedFile.ContentLength > 0 Then
-
Try
-
'checking if it was .txt file BEFORE UPLOADING IT!
-
'You used to upload it first...but the file could be a virus
-
If File1.FileName.EndsWith(".txt") = False Then
-
'The file is not the expected type...do not upload it
-
'just post the validation message
-
message.Text = "Please submit a text file."
-
Else
-
'The file is a .txt file
-
'checking to see if the file exists already
-
'If it does exist Deleting the existing one so that the new one can be created
-
If IO.File.Exists(SavePath) Then
-
IO.File.Delete(SavePath)
-
End If
-
-
'Now upload the file (save it to your server)
-
File1.PostedFile.SaveAs(SavePath)
-
-
'After saving it check to see if it exists
-
If File.Exists(SavePath) Then
-
'Upload was sucessful
-
message.Text = "Thank you for your submission"
-
fileWasUploaded = True
-
Else
-
'the file was not saved
-
message.Text = "Unable to save the file"
-
End If
-
End If
-
-
Catch Exc As Exception
-
'We encountered a problem
-
message.Text = Exc.Message + " " + Exc.StackTrace
-
End Try
-
Else
-
'No file was selected for uploading
-
message.Text = "Please select a file to upload"
-
End If
-
Return fileWasUploaded
-
End Function
-
-
Private Sub SaveToDatabase(ByVal SavePath As String)
-
Try
-
' and bulk import the data:
-
If ConfigurationManager.ConnectionStrings("Dialerresults") IsNot Nothing Then
-
Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
-
Dim results As New DataTable
-
-
Using con As New SqlConnection(connection)
-
con.Open()
-
-
' execute the bulk import
-
Using cmd As SqlCommand = con.CreateCommand
-
-
cmd.CommandText = "bulk insert dialerresults from '" & SavePath & "' " & _
-
"with ( fieldterminator = ',', rowterminator = '\n' )"
-
-
cmd.ExecuteNonQuery()
-
End Using
-
End Using
-
Else
-
message.Text="ConfigurationManager.ConnectionStrings('Dialerresults') is Nothing!"
-
End If
-
Catch ex As Exception
-
message.Text = ex.Message + ex.StackTrace
-
End Try
-
End Sub
-
End Class
At this time I'm not sure why you're getting an object not set to a reference
Change line 11 in my posted code to be the URL to the of the folder where you're uploading the files.
Frinny,
I also had to change line 10 to Protected Sub not Private Sub but now when I hit submit I get the following error:
ConfigurationManager.ConnectionStrings('Dialerresu lts') is Nothing!
Are you still getting the error message on page load?
I'm not getting that error anymore no. Now I'm just getting the
ConfigurationManager.ConnectionStrings('Dialerresu lts') is Nothing! error and no data is being posted to the database.
Is that message displayed without clicking the button?
Double check that your web.config <conectionStrings> section is correct.
It should be something like: -
<configuration>
-
<connectionStrings>
-
<add name="Dialerresults" connectionString="data source=src;initial catalog=tbl;user id=userID;password=passwordValue" providerName="System.Data.SqlClient"/>
-
</connectionStrings>
-
-
</configuration>
I didnt have the initial catalog in there but here's the connection string now:
<add name="Dialeresults" connectionString="server=10.2.1.40;data source=IVRDialer;initial catalog=dialerresults;uid=xxxx;password=xxxxxx;" providerName="System.Data.SqlClient" />
</connectionStrings>
This error is only happening after the upload button is pressed.
I don't know why you're getting this error message...it sounds like your application isn't configured properly.
For now try using a hard coded connection string (this is not a good idea to use when you release your code though).
I'm suggesting the following: - Private Sub SaveToDatabase(ByVal SavePath As String)
-
Try
-
' and bulk import the data:
-
'If ConfigurationManager.ConnectionStrings("Dialerresults") IsNot Nothing Then
-
'Dim connection As String = ConfigurationManager.ConnectionStrings("Dialerresults").ConnectionString
-
Dim connection As String = "server=10.2.1.40;data source=IVRDialer;initial catalog=dialerresults;uid=xxxx;password=xxxxxx;"
-
Dim results As New DataTable
-
-
Using con As New SqlConnection(connection)
-
con.Open()
-
-
' execute the bulk import
-
Using cmd As SqlCommand = con.CreateCommand
-
-
cmd.CommandText = "bulk insert dialerresults from '" & SavePath & "' " & _
-
"with ( fieldterminator = ',', rowterminator = '\n' )"
-
-
cmd.ExecuteNonQuery()
-
End Using
-
End Using
-
'Else
-
'message.Text="ConfigurationManager.ConnectionStrings('Dialerresults') is Nothing!"
-
'End If
-
Catch ex As Exception
-
message.Text = ex.Message + ex.StackTrace
-
End Try
-
End Sub
Ok so I changed the connection string so that now it's trying to upload a file and can see it but evidently, the page can't open the file because I get the following message:
Could not bulk insert because file 'C:\Inetpub\wwwroot\Webfile1\Data\upload.txt' could not be opened. Operating system error code 3(The system cannot find the path specified.). at System.Data.SqlClient.SqlConnection.OnError(SqlExc eption exception, Boolean breakConnection) at System.Data.SqlClient.SqlInternalConnection.OnErro r(SqlException exception, Boolean breakConnection) at System.Data.SqlClient.TdsParser.ThrowExceptionAndW arning(TdsParserStateObject stateObj) at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at System.Data.SqlClient.SqlCommand.RunExecuteNonQuer yTds(String methodName, Boolean async) at System.Data.SqlClient.SqlCommand.InternalExecuteNo nQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) at System.Data.SqlClient.SqlCommand.ExecuteNonQuery() at _Default.SaveToDatabase(String SavePath) in C:\Inetpub\wwwroot\Webfile1\Default.aspx.vb:line 78
Sign in to post your reply or Sign up for a free account.
Similar topics
by: R. Rajesh Jeba Anbiah |
last post by:
Q: How should I handle file upload?
A: File uploading requires HTML form of content type
"multipart/form-data". The file content has to be POSTed/submitted via
the form and once the file is...
|
by: ¦è»P¦èµ^ |
last post by:
Any homepage is for teaching file uploading in JAVA, JSP and TOMCAT, such as
JSPSmartUpload? thx very much
~ ªÑ²¼»ù®æ¦³¤É¦³¶^, ¶R½æn¯à©Ó¾á·ÀI ~
~ Samba, more than a low cost File and...
|
by: praba kar |
last post by:
Dear All,
I have doubt regarding file uploading. When we
upload a file to the remote server we can get file
type through file extentions. How we can find out file
type if a file doesn't have...
|
by: psb |
last post by:
WHO HAS THE BEST COMPONENT FOR FILE UPLOAD? HELP!? has anyone achieved
100% success with HTTP uploading with Mac clients??? I thought the whole
<input type="file" .../> was a w3c standard that...
|
by: Mukesh |
last post by:
Hi all
I am trying to upload and save as a picture to "root/Photos" folder in
my web application.
I am using this code to perform this task
DirectoryInfo strFolder = new...
|
by: ali |
last post by:
I am writing a script which uploads file to a specific directory; I am
using javascript to handle client side exceptions and php script which
actually performs file uploading.
Php scripts gets...
|
by: yatin.smile |
last post by:
I am a fresher in php and java script. that's wy i join a group for do
a discussion on different concepts of php and java scripts.
now i m working on file uploading.So i need a discussion on this...
|
by: ganesanji |
last post by:
hi all,
I have written a php coding for uploading a file to a specific folder or location in
server which is a Linux server. I think the coding for file uploaing is correct.
But it does not...
|
by: Raj |
last post by:
Hello,
I am planning to provide the Pause/Resume while uploading files.
Our site is using both java applet and activex to do this.
The list of selected files will be stored in an encrypted...
|
by: dmj07 |
last post by:
Can anybody help me with a simple file uploading and retrieving idea?
What I need is a simple system that uploads the files to be stored in a SQL database which are then shown on the front end in...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
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...
|
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,...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: 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 project—planning, coding, testing,...
|
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...
| |