Hi Everyone,
I was grateful to be able to download the code for uploading files into a folder from Sreedhar's web page. The code works well, but whenever there is another new file with the same file name being uploaded into the destination folder, the old file will be replaced. I am wondering if there is any way to solve this problem (How about adding a number to the new file's name, e.g. File1.doc, if there is an existing File.doc?) I am an absolute beginner and any help is deeply appreciated.
The original code is as follows:
<%
@ Page Language="VB" MasterPageFile="~/MasterPage.master" Title="Untitled Page" %><
script runat="server"> Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) If (FileUpload1.HasFile) Then Dim fileName As String = FileUpload1.FileNameFileUpload1.SaveAs(
"c:\temp\" & fileName)UploadStatusLabel.Text =
"Your file was saved as " & fileName ElseUploadStatusLabel.Text =
"Please provide a file to upload." End If End Sub</
script>
<
asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder2" Runat="Server"> <asp:FileUpload ID="FileUpload1" runat="server" /> <br /> <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" /> <br /> <asp:Label ID="UploadStatusLabel" runat="server" Text=""></asp:Label> </asp:Content>
Many thanks,
Tan
![]() |
0 |
![]() |
hello.
before saving the file use the File class to see if there's a file with the same name. the following example is simple but it may not work very well if you have several uploads done at the same time :
int i = 0;
string path = @"c:\Temp\" + filename
while( File.Exists( path ) ) //verify if file exists
{
path = path + i.ToString();
i++;
}
//here path should have a unique name (though this algorythm is not thread safe - regarding the name of the file)
//so you can just put the rest of the code here to save the file
btw, if i were you, i'd use a GUID as a filename because this will make it easier to garantee that there aren't 2 files with the same name (using guig will normally make you have to maintain a record for each file on a db)
--
Regards,
Luis Abreu
email: labreu_at_gmail.com
EN blog:http://msmvps.com/blogs/luisabreu
![]() |
0 |
![]() |
Hi Luis,
Thank you very much. However, it seems that your code is in C#, which I am not familiar with
Could you please convert it into Visual Basic code for me???
Furthermore, could you also show me what is GUID and how it can be used in uploading file?? I think GUID may be the right solution I should use for my little program.
Many thanks,
Tan
![]() |
0 |
![]() |
private function GetFileName(filename as string) as string
dim i as integer = 0
dim path as string = "c:\Temp\" & filename
do while File.Exists(path)
path = path & i.ToString()
loop
return path
end functionIf (FileUpload1.HasFile) Then
Dim fileName As String = GetFileName(FileUpload1.FileName)
FileUpload1.SaveAs(filename)
UploadStatusLabel.Text = "Your file was saved as " & fileName
Else
UploadStatusLabel.Text = "Please provide a file to upload."
End If
Brian O'Connell (MCAD) - http://www.systemdotweb.com
![]() |
0 |
![]() |
Hi Brian,
I get the error saying that: Name 'file' is not declared. I tried to add a line: Dim file As String as an attempt to solev the problem but it didn't work. Please help!!!![]()
Many thanks,
Tan
![]() |
0 |
![]() |
hello.
you must import the system.io namespace. if you're putting those lines on the aspx page you must add this:
<%@ Import Namespace="System.IO"%>
--
Regards,
Luis Abreu
email: labreu_at_gmail.com
EN blog:http://msmvps.com/blogs/luisabreu
![]() |
0 |
![]() |
Hi there,
Many thanks for the helps from Luis and Brian first...
The code works now. But, I noticed that whenever I tried to upload a file (regardless whether there is any file with similar file name), two copies of the file would be uploaded! This means that if I am uploading a file called ABC.pdf, the program would upload an ABC.pdf as well as creating an ABD.pdf0 in c:\temp even the c:\temp\ is empty. Any suggestion to solve the problem?
By the way, because the program will add an '0' to the end of the file extension (i.e. ABC.pdf0 instead of renaming it to 0ABC.pdf), I got a little problem to open the file. I tried to solve this problem by changing the path = path & i.ToString() to path = path & i.ToString() & filename. This creates a long a funny file names, such as ABC.pdf.ABC.pdf in c:\temp\. Any better way to sort this out?
Regards,
Tan
![]() |
0 |
![]() |
Can you post the exact code you are using.
Brian O'Connell (MCAD) - http://www.systemdotweb.com
![]() |
0 |
![]() |
My apologies. After I recopied the code and pasted onto a new .aspx page, the function did no longer create two files in one shot. However, I still do not manage to solve the problem where a "0" is placed at the end of the uploaded file's extension if similar file name exists. Any idea how to get this sorted out? Many thanks.
The codes is as follows:
<%
@ Page Language="VB" %><%
@ Import Namespace="System.IO" %><!
DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><
script runat="server"> Private Function GetFileName(ByVal filename As String) As String Dim i As Integer = 0 Dim path As String = "c:\Temp\" & filename Do While File.Exists(path)path = path & i.ToString()
Loop Return path End Function Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) If (FileUpload1.HasFile) Then Dim fileName As String = GetFileName(FileUpload1.FileName)FileUpload1.SaveAs(filename)
UploadStatusLabel.Text =
"Your file was saved as " & fileName ElseUploadStatusLabel.Text =
"Please provide a file to upload." End If End Sub</
script><
html xmlns="http://www.w3.org/1999/xhtml" ><
head runat="server"> <title>Untitled Page</title></
head><
body> <form id="form1" runat="server"> <div> <asp:FileUpload ID="FileUpload1" runat="server" /><br /> <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" /> <br /> <asp:Label ID="UploadStatusLabel" runat="server" Text=""></asp:Label></div> </form></
body></
html>
![]() |
0 |
![]() |
change the function to:-
Private Function GetFileName(ByVal filename As String) As String
Dim i As Integer = 0 Dim path As String = "c:\Temp\" & filename
dim fname as string = path.substring(0, path.indexof("."))
dim ext as string = path.substring(path.indexof("."))
Do While File.Exists(path)path = fname & i.ToString() & ext
Loop Return path End Function
Brian O'Connell (MCAD) - http://www.systemdotweb.com
![]() |
0 |
![]() |
hello.
i'm no vb.net expert, but shouldn't it be dim i as string?
--
Regards,
Luis Abreu
email: labreu_at_gmail.com
EN blog:http://msmvps.com/blogs/luisabreu
![]() |
0 |
![]() |
lol that was a conversion from your c# code but you do want to be easily able to increment it and as an integer it's more easily done then calling the tostring method allows you to append it. I always have Option Strict on but if it isn't on it will probably work without the tostring. Not a good practice though.
Brian O'Connell (MCAD) - http://www.systemdotweb.com
![]() |
0 |
![]() |
Hi there,
The program works, but if I upload the same file for the 3rd time, my computer hang...![]()
By the way, I had created a table called UploadFileTbl and would like to save the name of the file uploaded automatically into the table so that I can create a webpage for people to download the file. However, even though I know that this can be done, but I dont know how to do it. The table has only two columns, i.e. FileID (Primary, int) and Filename (Varchar). Can someone please enlighten me??
Many thanks
Tan
![]() |
0 |
![]() |
Private Function GetFileName(ByVal filename As String) As String
Dim i As Integer = 0 Dim path As String = "c:\Temp\" & filename
dim fname as string = path.substring(0, path.indexof("."))
dim ext as string = path.substring(path.indexof("."))
Do While File.Exists(path)i += 1
Loop Return path End Function
path = fname & i.ToString() & ext
I forgot to increment the i variable. As far as your table goes you haven't said how much you know about accessing databases. Are you saying you need to know from scratch how to access a database and update a table?
Brian O'Connell (MCAD) - http://www.systemdotweb.com
![]() |
0 |
![]() |
Hi Brian,
Thank you very much for your help. I really sorry for being slow in replying to your message as I was suffering from cold for a week and then was tied up with some other chores...
Anyway, I did do my home work and have learnt a bit more about how to insert data into tables.
I learned to write the codes to show User Name of the current logged in user in a text box (i.e. TextBox1.Text = User.Identity.Name()). However, my trial to insert the user name of the person who logged in automatically into a table without requiring him to retype his username still show no success. The codes are shown below. Is this a right/viable way?? Any suggestion?
Thanks in advance.
Regards,
Tan<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Upload_files.aspx.vb" Inherits="Upload_files" title="Untitled Page" %>
<
asp:Content ID="Content1" ContentPlaceHolderID="mainContentHolder" Runat="Server"> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" InsertCommand="INSERT INTO [Gallery] ([UploadedByMemberName], [FixtureID], [Notes], [PictureURL]) VALUES (@UploadedByMemberName, @FixtureID, @Notes, @PictureURL)" OldValuesParameterFormatString="original_{0}" > <InsertParameters> <asp:Parameter Name="UploadedByMemberName" DefaultValue=User.Identity.Name() Type="String" /> <asp:ControlParameter Name="FixtureID" ControlID="FixtureIDtextBox" Type="Int32" /> <asp:ControlParameter Name="Notes" ControlID="TextBoxNotes" PropertyName="Text" Type="String" /> <asp:ControlParameter Name="PictureURL" ControlID="FileUpload1" PropertyName="FileName" Type="String" /> </InsertParameters> </asp:SqlDataSource>Upload your photo from matches
<br /> <br />Please select the photo:
<asp:FileUpload ID="FileUpload1" runat="server" /><br /> <br />Uploaded by:
<asp:Label ID="Label1" runat="server"></asp:Label> <br /> <br />Fixture ID:
<asp:TextBox ID="FixtureIDtextBox" runat="server"></asp:TextBox><br /> <br />Comments:
<asp:TextBox ID="TextBoxNotes" runat="server"></asp:TextBox><br /> <br /> <asp:Button ID="Button1" runat="server" Text="Upload" /><br /> <asp:Label ID="FileUploadReport" runat="server"></asp:Label><br /> <br /> <br /></
asp:Content>
-------------------------------------------------------------------------------------------------------------------------------------------------Partial
Class Upload_files Inherits System.Web.UI.Page Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click If FileUpload1.HasFile Then TryFileUpload1.SaveAs(
"C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\Beta3\Photos\" & _FileUpload1.FileName)
Catch ex As ExceptionFileUploadReport.Text =
"Failed because: <br/>" & ex.Message End TryFileUploadReport.Text =
"File uploaded to Beta3 from <br/>" & _FileUpload1.PostedFile.FileName
SqlDataSource1.Insert()
ElseFileUploadReport.Text =
"Please select a file before clicking " & _ "the 'Upload' button" End If End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim UName As String = User.Identity.Name()Label1.Text = UName.ToString
End SubEnd
Class
![]() |
0 |
![]() |
The best way is to remove this:- DefaultValue=User.Identity.Name()
and overide the inserting event of the sqldatasource. Then set the value of the parameter
e.Command.Parameters("UploadedByMemberName").Value = User.Identity.Name()
Brian O'Connell (MCAD) - http://www.systemdotweb.com
![]() |
0 |
![]() |
Hi Brian,
Regards,
It's me againI had removed the DefaultValue=User.Identity.Name() and added the e.Command.Parameters("UploadedByMemberName").Value = User.Identity.Name() to the aspx.vb file. I dont know exactly how to override the inserting event of the sqldatasource. I tried with some combinations and none worked. Mind to help to to check what's wrong there? Thanks in advance...
Tan
Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Upload_files.aspx.vb" Inherits="Upload_files" title="Untitled Page" %><
asp:Content ID="Content1" ContentPlaceHolderID="mainContentHolder" Runat="Server"><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" InsertCommand="INSERT INTO [Gallery] ([UploadedByMemberName], [FixtureID], [Notes], [PictureURL]) VALUES (@UploadedByMemberName, @FixtureID, @Notes, @PictureURL)" OldValuesParameterFormatString="original_{0}" >
<InsertParameters>
<asp:Parameter Name="UploadedByMemberName"
Type="String" />
<asp:ControlParameter Name="FixtureID"
ControlID="FixtureIDtextBox"
Type="Int32" />
<asp:ControlParameter Name="Notes"
ControlID="TextBoxNotes"
PropertyName="Text"
Type="String" />
<asp:ControlParameter Name="PictureURL"
ControlID="FileUpload1"
PropertyName="FileName"
Type="String" />
</InsertParameters>
</asp:SqlDataSource>
Upload your photo from matches
<br />
<br />
Please select the photo:
<asp:FileUpload ID="FileUpload1" runat="server" /><br />
<br />
Uploaded by: <asp:Label ID="Label1" runat="server" Visible="False"></asp:Label>
<br />
<br />
Fixture ID:
<asp:TextBox ID="FixtureIDtextBox" runat="server"></asp:TextBox><br />
<br />
Comments:<asp:TextBox ID="TextBoxNotes" runat="server"></asp:TextBox><br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" /><br />
<asp:Label ID="FileUploadReport" runat="server"></asp:Label><br />
<br />
<br />
</asp:Content>
......................................................................................................................................................Partial Class Upload_files
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If FileUpload1.HasFile Then
TryFileUpload1.SaveAs(
"C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\Beta3\Photos\" & _FileUpload1.FileName)
Catch ex As ExceptionFileUploadReport.Text =
"Failed because: <br/>" & ex.Message End TryFileUploadReport.Text =
"File uploaded to Beta3 from <br/>" & _FileUpload1.PostedFile.FileName
SqlDataSource1.Insert()
ElseFileUploadReport.Text =
"Please select a file before clicking " & _ "the 'Upload' button" End If End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim UName As String = User.Identity.Name()Label1.Text = UName.ToString
End Sub Protected Sub SqlDataSource1_Inserted(ByVal sender As Object, ByVal e As SqlDataSourceCommandEventArgs)e.Command.Parameters(
"UploadedByMemberName").Value = User.Identity.Name() End SubEnd
Class
![]() |
0 |
![]() |
If you are using Visual Web Developer it's simple enough. In the code view select the sqldatasource1 in the dropdownlist on the top left, then select the inserting event (not inserted) from the top right dropdownlist. These events make sense if you think about them. The inserted event will happen after the data has been inserted in the database by the sqldatasource and the inserting event just before the data is inserted so you want to set the parameters before the data is inserted hence you overide the inserting event.
Brian O'Connell (MCAD) - http://www.systemdotweb.com
![]() |
0 |
![]() |
Hi Brian,
Thank you for telling me how to use that feature of VWD!!! That is one of the most important thing I learned from this forum. Now the automatic add username into the database function works smoothly. Thank you very much!!! Will start troubling you and everyone in this forum again in case I got any problem.
Regards,
Tan
p/s: The e.Command.Parameters("UploadedByMemberName").Value = User.Identity.Name() should be e.Command.Parameters("@UploadedByMemberName").Value = User.Identity.Name()
![]() |
0 |
![]() |
Hi Brian,
I modified some of the codes written by you (i.e. for the handling of duplicate filenames) for uploading multiple files. I tried to write the codes to save the ‘real’ file name of the file uploaded (which might be modified if the file name duplicates) into a table. However, I found that my code got a bug, i.e. if the file uploaded is saved as File2.doc in a folder, my code will record the file name as File3.doc into the table instead of File2.doc. How to solve this problem?
Many thanks
The codes is as follows:
<%@ Page Language="VB" %>
<%@ Import Namespace="System.IO" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
Private Function GetFileName(ByVal filename As String) As String
Dim i As Integer = 0
Dim path As String = "C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\WebSites\WebSite3AddFiles\Documents\" & "#" & filename
Dim fname As String = path.Substring(0, path.IndexOf("."))
Dim ext As String = path.Substring(path.IndexOf("."))
Do While File.Exists(path)
i += 1
path = fname & i.ToString() & ext
Loop
Return path
End Function
Protected Sub uploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If (FileUpload1.HasFile) Then
Dim fileName As String = GetFileName(FileUpload1.FileName)
FileUpload1.SaveAs(fileName)
End If
If (FileUpload2.HasFile) Then
Dim fileName As String = GetFileName(FileUpload2.FileName)
FileUpload2.SaveAs(fileName)
End If
If (FileUpload3.HasFile) Then
Dim fileName As String = GetFileName(FileUpload3.FileName)
FileUpload3.SaveAs(fileName)
End If
SqlDataSource1.Insert()
End Sub
Protected Sub SqlDataSource1_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs)
If FileUpload1.HasFile Then
Dim savedpath As String = GetFileName(FileUpload1.FileName)
Dim filenameOnly As String = savedpath.Substring(savedpath.IndexOf("#"))
e.Command.Parameters("@doc1").Value = filenameOnly.ToString
End If
If FileUpload2.HasFile Then
Dim savedpath As String = GetFileName(FileUpload2.FileName)
Dim filenameOnly As String = savedpath.Substring(savedpath.IndexOf("#"))
e.Command.Parameters("@doc2").Value = filenameOnly.ToString
End If
If FileUpload3.HasFile Then
Dim savedpath As String = GetFileName(FileUpload3.FileName)
Dim filenameOnly As String = savedpath.Substring(savedpath.IndexOf("#"))
e.Command.Parameters("@doc3").Value = filenameOnly.ToString
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>" DeleteCommand="DELETE FROM [SuggestionTable] WHERE [sugestionID] = @original_sugestionID AND [suggestion] = @original_suggestion AND [doc1] = @original_doc1 AND [doc2] = @original_doc2 AND [doc3] = @original_doc3 AND [submittedByUser] = @original_submittedByUser"
InsertCommand="INSERT INTO [SuggestionTable] ([suggestion], [doc1], [doc2], [doc3], [submittedByUser]) VALUES (@suggestion, @doc1, @doc2, @doc3, @submittedByUser)"
OldValuesParameterFormatString="original_{0}" SelectCommand="SELECT [sugestionID], [suggestion], [doc1], [doc2], [doc3], [submittedByUser] FROM [SuggestionTable]"
UpdateCommand="UPDATE [SuggestionTable] SET [suggestion] = @suggestion, [doc1] = @doc1, [doc2] = @doc2, [doc3] = @doc3, [submittedByUser] = @submittedByUser WHERE [sugestionID] = @original_sugestionID AND [suggestion] = @original_suggestion AND [doc1] = @original_doc1 AND [doc2] = @original_doc2 AND [doc3] = @original_doc3 AND [submittedByUser] = @original_submittedByUser" OnInserting="SqlDataSource1_Inserting">
<InsertParameters>
<asp:ControlParameter ControlID="TextBox1" Name="suggestion" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="FileUpload1" Name="doc1" PropertyName="FileName" Type="String" />
<asp:ControlParameter ControlID="FileUpload2" Name="doc2" PropertyName="FileName" Type="String" />
<asp:ControlParameter ControlID="FileUpload3" Name="doc3" PropertyName="FileName" Type="String" />
<asp:Parameter Name="submittedByUser" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
</div>
<br />
<table style="width: 800px">
<tr>
<td style="width: 100px">
</td>
<td width="700">
</td>
</tr>
<tr>
<td style="width: 100px; height: 132px">
Suggestion:</td>
<td style="height: 132px" width="700">
<asp:TextBox ID="TextBox1" runat="server" Height="120px" TextMode="MultiLine" Width="540px"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Relevant Doc:
</td>
<td width="700">
<asp:FileUpload ID="FileUpload1" runat="server" /></td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td width="700">
<asp:FileUpload ID="FileUpload2" runat="server" /></td>
</tr>
<tr>
<td style="width: 100px; height: 19px;">
</td>
<td width="700" style="height: 19px">
<asp:FileUpload ID="FileUpload3" runat="server" /></td>
</tr>
<tr>
<td style="width: 100px">
</td>
<td width="700">
<asp:Button ID="uploadButton" runat="server" Text="Upload" OnClick="uploadButton_Click" /></td>
</tr>
</table>
</form>
</body>
</html>
![]() |
0 |
![]() |