I'm trying to develop a website with File upload and download option using vb.net and asp.net with Visual Studio 2008. Can anyone help me about how can I provide the facility of uploading a file into the server and then a download link will be available for the common users to download the file from the server. Thanks in advance.
Use FileUpLoad control.
Here is a sample for uploading (in c#) :
http://www.c-sharpcorner.com/UploadFile/mahesh/FileUpload10092005172118PM/FileUpload.aspx
You can use asp:FileUpload control to upload file to your server, a location with permission to write file
FileUpload control overview
FileUpload example
It's as simple as putting the control in your .aspx file
<asp:FileUpload runat="server" ID="MyFileUpload" />
Codebehind
If (MyFileUpload.HasFile) Then
MyFileUpload.SaveAs('the full path to directory ' & filename)
End If
You can store the file description in database with their path, retrieve this on your page and display to user
You can also browse your directory and list the files on your page
Dim FileToCopy As String
FileToCopy = "F:\fd_demo_limits.swf"
Dim filenameTest = System.IO.Path.GetFileName(FileToCopy)
Dim path As String = "E:\"
Dim filename As String = "communicate.png"
Dim file_ As New System.IO.FileInfo(path + filename)
Dim file_ContentLength As String = "900000" ' check file Length file_.Length = 833740
If (file_.Length > file_ContentLength) Then
MsgBox("file length is large")
Exit Sub
End If
Dim allow_send_pic() As String = {".jpg", ".png", ".gif", "ico", ".png"}
Dim Extension As String = System.IO.Path.GetExtension(filename)
If Array.IndexOf(allow_send_pic, Extension.ToLower()) = -1 Then
MsgBox("File extension not valid")
Exit Sub
End If
If System.IO.File.Exists(FileToCopy) = True Then
While (System.IO.File.Exists(path + filename))
filename = "Copy of " + filename
End While
System.IO.File.Copy(FileToCopy, path + filename)
MsgBox("File Copied")
End If
Related
My asp.net web app requires downloading files from DropBox.
In DropBox, I created an app and have the API key and Auth Token, Secret, etc.
In my web app I have reference to Dropbox.Api and can create DropboxClient.
Like so:
Dim myDBClient As New DropboxClient("my_token_auth")
What do I do next? Does anyone have sample code.
I read I need to call async method to download such as code below.
But the code is not working. Not failing either but does nothing.
Any help would be appreciated. Thank you
Dim folder As String = "C:\Data"
Dim file2 As String = "myFile.txt"
Using response = myDBClient.Files.DownloadAsync("/" & folder & "/" & file2)
Using fileStream = File.Create("C:\Data\myFile.txt")
(response.GetContentAsStreamAsync()).CopyTo(fileStream))
End Using
End Using
You need to use Await to get the expected result.
Demo code:
Dim myDbClient As New DropboxClient("auth token")
Dim folder = "test" 'dropbox folder name
Dim fileName = "1.txt" 'dropbox file name
Dim response As IDownloadResponse(Of FileMetadata) = Await myDbClient.Files.DownloadAsync("/" + folder + "/" + fileName)
Dim bytes = Await response.GetContentAsByteArrayAsync()
Using fileStream = Create("D:\tom\2.txt") ' local path
fileStream.Write(bytes, 0, bytes.Length)
End Using
Update:
Add the detail test steps:
1.Create dropbox app and generate the auth token.
2.Create the folder and upload the file to dropbox folder
3.Create an Asp.net empty project and add a webform.aspx file named DropBoxApiTest.aspx and set it as start page.
4.To install Dropbox.Api, run the following command in the Package Manager Console:
PM> Install-Package Dropbox.Api
5.Add the download button in the Webpage
<asp:Button ID="_btnDownload" runat="server" Text="Download" />
6.Add the click event for the button and the following code.
Protected Async Sub _btnDownload_Click(sender As Object, e As EventArgs) Handles _btnDownload.Click
Dim token = "xaMln4bUnRAAAAAAAAAAIq...."
Dim myDbClient As New DropboxClient(token)
Dim folder = "test" 'dropbox folder name
Dim fileName = "1.txt" 'dropbox file name
Dim response As IDownloadResponse(Of FileMetadata) = Await myDbClient.Files.DownloadAsync("/" + folder + "/" + fileName)
Dim bytes = Await response.GetContentAsByteArrayAsync()
Using fileStream = Create("D:\tom\download.txt") ' local path
fileStream.Write(bytes, 0, bytes.Length)
End Using
End Sub
7.We also need to change aspx Async to true
8.Test it locally.
I have look for days, with no luck.
Can anyone tell me how to save files in VB.Net to any computer? There are lost of articles, but those only tell you about saving to your own computer by giving folder access, not a random user's computer.
You can see my example here http://hanontest.com/POShellCreator.aspx (You have to enter text into task code, project id and notes field, then click create. Then click export, you will see the error.)
I can go to a local Pizza shop website and download a menu pdf, I know its possible.
In my example it saves when you click the button, I would like a save as dialog if anyone knows how to do that as well.
Here is the save string:
Dim regDate As Date = Date.Now()
Dim strDate As String = regDate.ToString(".yyyy\.MM\.dd")
TextBox5.Text = "c:\temp\" & Vendor & "&" & Vendor2 & "&" & Vendor3 & "&" & Vendor4 & TaskEmpty & strDate & ".csv"
Here is how I am saving:
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Define Path to save file.
Dim path As String = TextBox5.Text
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes(TextBox3.Text)
fs.Write(info, 0, info.Length)
fs.Close()
End Sub
The error you're seeing there is because you're attempting to save the text file to the server's
file system, which you don't have write access to.
To return a file to user from the server you need to do a little more work, and it's not going to simple on a postback from a button.
You need to send the data down to the client in the Response.OutputStream, instead of your page, and also tell the browser to treat it as a file download:
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=textFile.csv");
This is related to my previous question. An unforeseen issue arose with the Wizard control.
I now know how to upload to FTP, however when using the FileUpload control inside a Wizard control, when you move to the next step, the File you selected gets cleared because of the postback. I need to be able to rename the file according to the results from the Wizard before uploading. So...
I finish my wizard
It uploads some stuff to a database
Renames the file according to those results
Uploads the renamed file to the FTP server
I suspect I will need to follow a procedure something like this, having an upload button next to FileUpload
On "Upload" button click stream the file to the Web Server.
Complete the Wizard.
If the wizard completes successfully, rename file and stream to FTP server.
If the wizard fails, what? Delete the file from the web server? How?
I think I understand the process, so I would like help on how to split my FTP Upload function into two parts with the proper error handling for when the wizard fails.
It would be a great help if you please use the following code as a base. Thanks as always :)
Protected Sub UploadFile(ByVal NewFilename As String)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
'Function one? - Problem, "NewFilename" depends on the output of the Wizard,
' but obviously it has not been called yet.
myFtpWebRequest = CType(WebRequest.Create(ftpServer + ftpPath + NewFilename), FtpWebRequest)
myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True
Dim myFileStream As Stream = FileUpload1.FileContent
myFtpWebRequest.ContentLength = myFileStream.Length
'Function two?
Dim requestStream As Stream = myFtpWebRequest.GetRequestStream()
myFileStream.CopyTo(requestStream)
requestStream.Close()
myFtpWebResponse = CType(myFtpWebRequest.GetResponse(), FtpWebResponse)
myFtpWebResponse.Close()
End Sub
-- ANSWER ---
Here's my final implementation based on input from Icarus :)
For brevity I have excluded the error catching.
'This function is what kicks things off...
Protected Sub UploadFileToWebServer() Handles btnUploadFile.Click
Dim TempDir As String = "C:\TEMP", FileName As String = "uploadedfile.tmp", FilePath As String
If Not Directory.Exists(TempDir) Then
Directory.CreateDirectory(TempDir).Attributes = FileAttributes.Directory
End If
FilePath = TempDir + "\" + FileName
Session.Add("FileName", File1.FileName) 'Keep track of uploaded file name
File1.SaveAs(FilePath)
Session.Add("File", FilePath)
End Sub
After the file is uploaded to the web server, we can continue through the wizard, and when the "Finish" button is clicked, the wizard data gets submitted to the database. The filename is based on the inserted record ID. The following function gets called by the "Final" button click after the record is inserted, and the file finally gets uploaded to the FTP server with the filename changed accordingly.
Protected Sub UploadFileToFtpServer(ByVal FileLinkStr As String)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
'Defines the filename, path, and upload method, and connection credentials
myFtpWebRequest = CType(WebRequest.Create(ftpServer + ftpPath + FileLinkStr), FtpWebRequest)
'Be sure to authenticate prior to uploading or nothing will upload and no error
myFtpWebRequest.Credentials = New NetworkCredential(ftpUsername, ftpPassword)
myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True
'Streams the file to the FTP server
'Retrieves File temporarily uploaded to the Web Server during Wizard Processing
Dim iStream As New FileInfo(Session.Item("File"))
Dim myFileStream As Stream = iStream.OpenRead
myFtpWebRequest.ContentLength = myFileStream.Length
Dim requestStream As Stream = myFtpWebRequest.GetRequestStream()
myFileStream.CopyTo(requestStream)
requestStream.Close()
myFtpWebResponse = CType(myFtpWebRequest.GetResponse(), FtpWebResponse)
myFtpWebResponse.Close()
End Sub
Your understanding is correct. Once you upload the file to the web server (you'd need to place it in a temp directory somewhere and keep track of the file name you gave it) and the wizard completes successfully, you grab that file, rename it accordingly and upload it to the ftp server. If fails, simply call:
File.Delete(Path_to_file_uploaded_on_temp_directory);
You can keep track of the file name given originally, by storing it in Session, for example. When you upload the file to the server initially, do something like Session["FileName"]=Path_to_temp_directory+fileName;
On the final step of the Wizard, get the file name from Session and either rename it and upload it to the FTP Server or delete it.
Of course you need to account for possible name conflicts, etc. You can use a Guid to generate a random name for the file, for example.
I hope I explained this clearly.
EDIT
To make sure I understand correctly...
You need your user to go through all the steps of a Wizard kind of thing
During the process, you ask your user to upload a file.
Because the user has to select a file before the last step of the wizard, you are forced to upload the file immediately the user clicks on the "Next" button to go to the next step of the wizard.
At the very last step of the Wizard, you need to determine whether the file the user has selected should be uploaded to an ftp server (presumably, another box different from your web server) or should be discarded completely.
If the file needs to be uploaded to the FTP server, it needs to be renamed with a special name.
Based on the above, my suggestion is:
When the user clicks "Next" on the step where he selects the file from his computer, you need to save the file immediately to a temporary location on your web server. You save the file to this temporary folder on your web server by doing something like:
if(FileUpload1.HasFile) //user selected a file
{
try
{
//D:\temp is a temp directory on the Web Server
FileUpload1.PostedFile.SaveAs(#"D:\temp\"+FileUpload1.FileName);
//Store the FULL PATH TO the file just uploaded on Session
Session["FileName"]="D:\temp\"+FileUpload1.FileName;
}
catch (Exception ex)
{
//Handle it.
}
}
On the last step of the wizard, assuming everything was successful, do this
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
' You know the NewFileName because it's the output of the wizard
myFtpWebRequest = CType(WebRequest.Create(ftpServer + ftpPath + NewFilename), FtpWebRequest)
myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True
'Here you need to read the Original File
Dim myFileStream As Stream = new FileStream(Session["FileName"]),FileMode.Open,FileAccess.Read,FileShare.ReadWrite)
myFtpWebRequest.ContentLength = myFileStream.Length
Dim requestStream As Stream = myFtpWebRequest.GetRequestStream()
myFileStream.CopyTo(requestStream)
requestStream.Close()
myFtpWebResponse = CType(myFtpWebRequest.GetResponse(), FtpWebResponse)
myFtpWebResponse.Close()
If you decide that you should delete the original file uploaded by the user because he did not complete the wizard successfully, you can simply do:
try
{
File.Delete (Session["FileName"]);
}
catch(Exception ex)
{
//Handle it.
}
My sql query is returning records from the database that contains a filename. I will be appending the filepath (from the web.config file) to allow the user to download the complete file. However, another colum in the grid, has to be the file size.
How can I obtain the filesize, given that the name is being returned from the database, and the filepath is from the web.config file?
Thanks
One way to do it is to store the size of the pdf file upon your upload of the file to the server and then just retrieve it along with the file name.
Using System.IO you can get the filesize
Dim f As New FileInfo("thefullfilepath")
Dim i As Integer = f.Length
EDIT: Use Import System.IO for VB
string MyFile = "~/files/my.pdf";
FileInfo finfo = new FileInfo(Server.MapPath(MyFile));
long FileInBytes = finfo.Length;
long FileInKB = finfo.Length / 1024;
Use the FileInfo class:
' Build the string fileName from path stored in Web.Config and the filename
' returned from the database
Dim fileName As String = "your path and filename"
Dim fInfo As FileInfo = new FileInfo(fileName)
Dim fileSize As Long = fInfo.Length
You will probably need to do this in the RowDataBound event, assuming your binding your GridView to a datasource (like your SQL query).
I am trying to import some data from an excel spreadsheet, using VB.net
my steps are:
first the user uploads the file to the server
then i want to read the file from the server to then populate a gridview
this is what i have:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim filepath As String = ""
If FileUpload1.HasFile Then
Try
If (FileUpload1.PostedFile.ContentType = "application/vnd.ms-excel") Then
Dim filename As String = Path.GetFileName(FileUpload1.FileName)
'Session("userid") & "-" & Date.Now()
filepath = "\excel\" & Session("userid") & "_" & Now.Date().ToString("Mdy") & "_" & filename
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
ReadExcel(filepath)
Else
StatusLabel.Text = "Only Excel file types are accepted"
End If
Catch ex As Exception
StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message
End Try
End If
End Sub
Sub ReadExcel(ByVal filepath As String)
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & filepath & "';Extended Properties=Excel 8.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [NSTS]", MyConnection)
MyCommand.TableMappings.Add("Table", "Net-informations.com")
DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)
gwResults.DataSource = DtSet.Tables(0)
MyConnection.Close()
End Sub
the error happens with "MyConnection", it tried to look on the "C:/" instead of on the server:
'c:\excel\3_41911_Sample.xls' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.
how can i set the OleDb connection to get the source file from the server instead?
thank you!
nevermind, i got it
i added: Server.MapPath("~/") & filepath and now it works. however, now i'm getting the error:
The Microsoft Jet database engine could not find the object 'NSTS'. Make sure the object exists and that you spell its name and the path name correctly.
NSTS is the name of my first spreadsheet. what am i doing wrong? :(
i was missing a studip dollar sign :) ahh, it all works now!
"select * from [NSTS$]"
thanks!
Use a $ in your sheet's name in the query:
"select * from [NSTS$]"
Your c:\excel\ path is not local path but it is path local to where you are running your application.
If you are running this application from local machine, In order to map c:\excel\ path, you should either map server drive to your windows and use that drive name OR use \\excel as path value.
First - do you know exactly where on the server path the file is being saved to? I'd begin by hardcoding the path to make sure that there isn't anything else squirrely going on.
Looking at your code you're saving the file here...
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
So... first, are you sure it's saving there? If so then look as where you're reading the file with this call...
ReadExcel(filepath)
Have you tried -
ReadExcel(Server.MapPath("~/") & filepath)?