Upload File to FTP Server via Command Shell

How to FTP using Windows Command Prompt

Go to the Start Menu and Click Run…
kb-global-start-run

In the Run dialog box, type cmd and click OK

kb-global-cmd-300x148

The Windows Command Prompt will open. Type the following command to connect to your server:

ftp yourdomain.com

Where yourdomain.com is your domain or the FTP Server IP Address found in the HELM Control Panel under the FTP Account Details.

kb-cmdftplogin

Once you hit Enter it will attempt to connect to the server. If it is successful, you will be prompted for a Username and Password. Enter the FTP username and password information to login.

Once you have Logged in, you should see a line like ftp>

To list the Directory Contents, use the command dir

kb-cmdftplogindir-300x149

You have successfully connected to your server through FTP using Windows Command Prompt.

More FTP Commands:

ABOR – abort a file transfer
CWD – change working directory
DELE – delete a remote file
LIST – list remote files
MDTM – return the modification time of a file
MKD – make a remote directory
NLST – name list of remote directory
PASS – send password
PASV – enter passive mode
PORT – open a data port
PWD – print working directory
QUIT – terminate the connection
RETR – retrieve a remote file
RMD – remove a remote directory
RNFR – rename from
RNTO – rename to
SITE – site-specific commands
SIZE – return the size of a file
STOR – store a file on the remote host
TYPE – set transfer type
USER – send username

Automating File Uploads

Create a commands file (in my example it is named commands.txt).

Type the following in your commands.txt:

open FTP_ADDRESS
FTP_USERNAME
FTP_PASSWORD
put FILENAME

!del FILENAME
bye

Any commands starting with “!” will be executed on the local server rather than the remote server. Remove the line marked in Red if you would like to keep the files on the source server after the upload has been finished.

To execute these commands type in the windows command prompt:

ftp -s:commands.txt

This command will execute the script.

If you would like to automate the file upload, create a MS-DOS batch file with notepad ( extension needs to be .cmd or .bat) and save the above FTP command. You can now use this file to create scheduled tasks and run it at specific intervals.

To find out how to use VBScript instead, check out yesterday’s article on FTP File Uploads.

Upload file to FTP Server via VBS Script

We always requirements to put files on a server without installing additional software on the source server.

An easy way to accomplish this is by using VBS (Visual Basic Scripts).

 

Using Chilkat FTP

One method is to use the Chilkat FTP Software (1 license costs about $289). You can install a 30-day trial version by clicking here.

 

Dim fso, outFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set outFile = fso.CreateTextFile("output.txt", True)

' This CreateObject statement uses the new single-DLL ActiveX for v9.5.0
set ftp = CreateObject("Chilkat_9_5_0.Ftp2")

'  Any string unlocks the component for the 1st 30-days.
success = ftp.UnlockComponent("Anything for 30-day trial")
If (success <> 1) Then
    outFile.WriteLine(ftp.LastErrorText)
    WScript.Quit
End If

ftp.Hostname = "ftp.chilkatsoft.com"
ftp.Username = "****"
ftp.Password = "****"

'  The default data transfer mode is "Active" as opposed to "Passive".

'  Connect and login to the FTP server.
success = ftp.Connect()
If (success <> 1) Then
    outFile.WriteLine(ftp.LastErrorText)
    WScript.Quit
End If

'  Change to the remote directory where the file will be uploaded.
success = ftp.ChangeRemoteDir("junk")
If (success <> 1) Then
    outFile.WriteLine(ftp.LastErrorText)
    WScript.Quit
End If

'  Upload a file.
localFilename = "c:/temp/hamlet.xml"
remoteFilename = "hamlet.xml"

success = ftp.PutFile(localFilename,remoteFilename)
If (success <> 1) Then
    outFile.WriteLine(ftp.LastErrorText)
    WScript.Quit
End If

ftp.Disconnect

MsgBox "File Uploaded!"
outFile.Close

Free Version

The example VBS script below shows how to upload and save a local file to a remote webserver using Microsoft VBS scripting. The upload method in this example is HTTP PUT, meaning that the webserver needs to be WebDAV-enabled. Since file upload is typically password-protected, the script implements access with basic authentication.

'======================================================================
' https-upload.vbs 1.0  @2009 by Frank4dd http://www.frank4dd.com/howto
' This script demonstrates a file upload to a WebDAV enabled webserver,
' using https (and proxy settings from IE) with basic web authentication
'
' Original authors and code references:
' - "ASP - File upload with HTTP Put" by Martin Clark
'
' This program comes with ABSOLUTELY NO WARRANTY. You may redistribute
' copies of it under the terms of the GNU General Public License.
'======================================================================

'======================================================================
' Global Constants and Variables
'======================================================================
Const scriptVer  = "1.0"
Const UploadDest = "https://mywebdavserver.com/uploadurl"
Const UploadFile = "localpath-and-file"
Const UploadUser = "username"
Const UploadPass = "password"
Const UploadType = "binary"
dim strURL

function sendit()
  sData = getFileBytes(UploadFile, UploadType)
  sfileName= mid(UploadFile, InstrRev(UploadFile,"")+1,len(UploadFile))

  dim xmlhttp
  set xmlhttp=createobject("MSXML2.XMLHTTP.3.0")
  strURL = UploadDest & "/" & UploadFile
  msgbox "Upload-URL: " & strURL
  xmlhttp.Open "PUT", strURL, false, UploadUser, UploadPass
  xmlhttp.Send sData
  Wscript.Echo "Upload-Status: " & xmlhttp.statusText
  set xmlhttp=Nothing
End function

function showresult()
  Wscript.Echo "Complete. Check upload success at: " & strURL
end function

function getFileBytes(flnm, sType)
  Dim objStream
  Set objStream = CreateObject("ADODB.Stream")
  if sType="binary" then
    objStream.Type = 1 ' adTypeBinary
  else
    objStream.Type = 2 ' adTypeText
    objStream.Charset ="ascii"
  end if
  objStream.Open
  objStream.LoadFromFile flnm
  if sType="binary" then
    getFileBytes=objStream.Read 'read binary'
  else
    getFileBytes= objStream.ReadText 'read ascii'
  end if
  objStream.Close
  Set objStream = Nothing
end function

'=======================================================================
' End Function Defs, Start Main
'=======================================================================
' Get cmdline params and initialize variables
If Wscript.Arguments.Named.Exists("h") Then
  Wscript.Echo "Usage: https-upload.vbs"
  Wscript.Echo "version " & scriptVer
  WScript.Quit(intOK)
End If

sendit()
showresult()
Wscript.Quit(intOK)
'=======================================================================
' End Main
'=======================================================================

Rewrite URLs on the Fly (Classic ASP)

Use HttpContext.RewritePath to “fake” URLs within an application.

One of the more obscure – but potentially useful – methods in the portion of the .NET Framework that comprises ASP.NET is the HttpContext class’s RewritePath method. Used internally by ASP.NET to strip session IDs from URLs when cookieless session state is enabled, RewritePath can also be used to “fake” URLs within an application. To demonstrate, consider the following ASPX file, which we’ll call RewritePath.aspx:

<html>
<body>
<h2><asp:Label ID=”Output” RunAt=”server” /></h2>
</body>
</html>

void Page_Load (Object sender, EventArgs e)
{
string id = Request.QueryString[“ID”];
if (id != null && id != String.Empty) {

switch (id) {

case “1”:

Output.Text = “Give me chastity and ” + “continence, but not yet.”;
break;

case “2”:

Output.Text = “A programmer is a device ” + “for turning coffee into code.”;
break;

case “3”:

Output.Text = “Blessed is the man who, ” + “having nothing to say, abstains from ” + “giving wordy evidence of the fact.”;
break;

}

}

}

If this page is deployed in a virtual directory named Foo, then the following URLs invoke the page and display three different quotations:
http://…/foo/rewritepath.aspx?id=1
http://…/foo/rewritepath.aspx?id=2
http://…/foo/rewritepath.aspx?id=3

So far, so good. Now suppose that you’d like users to be able to display these quotations by typing the following “phantom” URLs:

http://…/foo/quotes/page1.aspx
http://…/foo/quotes/page2.aspx
http://…/foo/quotes/page3.aspx

You can accomplish this little bit of magic – converting a URL of the form …/quotes/page1.aspx into a URL of the form …/rewritepath.aspx?id=1 on the fly – with HttpContext.RewritePath. The trick is to grab each request for /quotes/page1.aspx, /quotes/page2.aspx, and so on as it enters ASP.NET’s HTTP pipeline and convert it into a request for /rewritepath.aspx?id=1, /rewritepath.aspx?id=2, and so on. Here’s a Global.asax file that does just that:

void Application_BeginRequest (Object sender, EventArgs e)
{
// TODO: Convert a path of the form
// …/quotes/page1.aspx into a path of the form
// …/rewritepath.aspx?id=1

HttpContext context = HttpContext.Current;

string oldpath = context.Request.Path.ToLower ();
string token = “/quotes/page”;
int i = oldpath.IndexOf (token);
int len = token.Length;
if (i != -1) {

int j = oldpath.IndexOf (“.aspx”);
if (j != -1) {

string id = oldpath.Substring (i + len, j – (i + len));
string newpath = oldpath.Replace (token + id + “.aspx”, “/rewritepath.aspx?id=” + id);
context.RewritePath (newpath);
}

}

}

Application_BeginRequest fires at the beginning of every request. This implementation extracts the path portion of the URL targeted by the request (for example, /foo/quotes/page1.aspx), replaces it with a path that refers to the real page (for example, /foo/rewrite.aspx?id=1), and calls RewritePath to retarget the request. Try it: Drop RewritePath.aspx into wwwroot on your Web server and try to invoke it by typing this URL into your browser’s address bar:

http://localhost/quotes/page1.aspx

That should generate a “page not found” error. Now copy Global.asax to wwwroot and try again. This time, it should work just fine, thanks to the indirection afforded by Application_BeginRequest.

RewritePath has many applications. You can use it, for example, to convert query strings into path names so pages that use query string parameters to drive content can be bookmarked in browsers. You can also use it to obfuscate path names within your application for security reasons. Now that you know RewritePath exists, you may find other uses for it, too.

By Jeff Prosise

Formatting numbers with Classic ASP

Format Numbers – Reference

Frequently you want a number to appear in a certain format. The most commands requests are for a set total number of digits and a set number of digits to the right of the decimal place. Less frequently there is a call for negative amounts displayed in parenthesis or that there should be leading zeros.

The FormatNumber function takes the contents of a number type variable and returns the contents in the specified format.

Syntax: FormatNumber(expression, iDigits, bleadingDigit, bParen, bGroupDigits)

argument meaning
expression the variable holding the raw number
iDigits number of digits to right of decimal point
bleadingDigit 1 for leading zeros
0 for no leading zeros
bParen 1 for parenthesis around negative numbers
0 for no parenthesis around negative numbers
bGroupDigits 1 to display numbers as per regional settings in the Control Panel
0 to over-ride settings in the Control Panel

<html><head>
<TITLE>formatnumbers2.asp</TITLE>
</head><body bgcolor=”#FFFFFF”>
<%
 My ASP formatting number sample
mynumber=123.4567
response.write “<hr>” & mynumber & “<br>”
response.write “formatnumber(mynumber,0)” & “<br>”
response.write formatnumber(mynumber,0) & “<hr>”
response.write “formatnumber(mynumber,2)” & “<br>”
response.write formatnumber(mynumber,2) & “<hr>”
response.write “formatnumber(mynumber,6)” & “<br>”
response.write formatnumber(mynumber,6) & “<hr>”

mynumber=.4567
response.write mynumber & “<br>”
0 means means no leading zeroes
response.write “formatnumber(mynumber,2,0)” & “<br>”
response.write formatnumber(mynumber,2,0) & “<hr>”
1 means means pad with leading zeroes
response.write “formatnumber(mynumber,2,1)” & “<br>”
response.write formatnumber(mynumber,2,1) & “<hr>”

mynumber=-123.4567
response.write mynumber & “<br>”
0 means means no parentheses for negative numbers
response.write “formatnumber(mynumber,2,0,0)” & “<br>”
response.write formatnumber(mynumber,2,0,0) & “<hr>”
1 means means yes parentheses for negative numbers
response.write “formatnumber(mynumber,2,0,1)” & “<br>”
response.write formatnumber(mynumber,2,0,1) & “<hr>”
%>
</body></html>

Displaying Table Data with Classic ASP

This page demonstrates the capabilities how to display a table from a SQL statement.

 

<html><head>
<TITLE>dbsimple.asp</TITLE>
</head>
<body bgcolor=”#FFFFFF”>
<%
 this code opens the database
myDSN=”DSN=Student;uid=student;pwd=magic”
set conntemp=server.createobject(“adodb.connection”)
conntemp.open myDSN

 this code retrieves the data
mySQL=”select * from publishers where state=NY
set rstemp=conntemp.execute(mySQL)

 this code detects if data is empty
If  rstemp.eof then
response.write “No records matched<br>”
response.write mySQL & “<br>So cannot make table…”
connection.close
set connection=nothing
response.end
end if
%>
<table border=1>
<%
 This code puts fieldnames into column headings
response.write “<tr>”
for each whatever in rstemp.fields
response.write “<td><B>” & whatever.name & “</B></TD>”
next
response.write “</tr>”

 Now lets grab all the records
DO  UNTIL rstemp.eof
 put fields into variables
pubid=rstemp(“pubid”)
name=rstemp(“name”)
company_name=rstemp(“company name”)
address=rstemp(“address”)
city=rstemp(“city”)
state=rstemp(“state”)
zip=rstemp(“zip”)
telephone=rstemp(“telephone”)
fax=rstemp(“fax”)
comments=rstemp(“comments”)

 write the fields to browser
cellstart=”<td align=””top””>”
response.write “<tr>”
response.write cellstart & pubid & “</td>”
response.write cellstart & name & “</td>”
response.write cellstart & company_name & “</td>”
response.write cellstart & address & “</td>”
response.write cellstart & city & “</td>”
response.write cellstart & state & “</td>”
response.write cellstart & zip & “</td>”
response.write cellstart & telephone & “</td>”
response.write cellstart & fax & “</td>”
response.write cellstart & comments & “</td>”

response.write “</tr>”
rstemp.movenext
LOOP
%>
</table>

<%
 Now close and dispose of resources
rstemp.close
set rstemp=nothing
conntemp.close
set conntemp=nothing
%>

</body></html>

Select Case in Classic ASP

Using IF-THEN can be cumbersome, prone to programmer errors and slower to execute. A more efficient construct is SELECT CASE. It is optimized for testing one variable against many conditions.

<html><head>
<TITLE>case2.asp</TITLE>
</head><body bgcolor="#FFFFFF">
<form action="case2respond.asp" method="get">
Your First Name<INPUT NAME="FirstName" MaxLength=20><p>
Your Last Name<INPUT NAME="LastName" MaxLength=20><p>
Your Title
<INPUT TYPE="Radio" name="Title" VALUE="employee">Entry Level
<INPUT TYPE="Radio" name="Title" VALUE="temp" CHECKED>Temporary Employee
<INPUT TYPE="Radio" name="Title" VALUE="manager">Management Candidate
<INPUT TYPE="Radio" name="Title" VALUE="executive">Executive
<INPUT TYPE="Radio" name="Title" VALUE="vice-prez">The Vice President of...
<INPUT TYPE="Radio" name="Title" VALUE="CEO">The Boss<p>
<INPUT TYPE=submit><p>
</form>
</body></html>

Here is the select case that will determine what the form input means.

<html><head>
<TITLE>case2respond.asp</TITLE>
</head><body bgcolor="#FFFFFF">
<%
fname=request.querystring("Firstname")
lname=request.querystring("Lastname")
title=request.querystring("title")
response.write "Nice to Hire You " & fname & " " & lname & "<p>"
Select Case lcase(Title)
case "employee","temp"
response.write("The washroom is in the hall")
case "manager","executive"
response.write("Here is your key to the Executive washroom")
case "ceo", "vice-prez"
response.write("The maid will attend to your private washroom")
End Select%>
</body></html>

Add new record to the database using Classic ASP

Please note the code below. This sequence will add a new record into a database.

The database is identified by the DSN name and is called Student.

Option 1

The code below can be called by passing the parameteres in the query string like: dbnewrecSQL.asp?name=Joey&id=9000&year=1964

<TITLE>dbnewrecSQL.asp</TITLE>
<body>
<HTML>
<%
'on error resume next
auname=request.querystring("name")
auyear=request.querystring("year")
auID=request.querystring("ID")
If  auid<9000 then
auid=auid+9000
end if
Set Conn = Server.CreateObject("ADODB.Connection")
conn.open "DSN=Student;uid=student;pwd=magic"
SQLStmt = "INSERT INTO authors (AU_ID,author,year_born) "
SQLStmt = SQLStmt & "VALUES (" & auid
SQLStmt = SQLStmt & ",'" & auname & "'"
SQLStmt = SQLStmt & "," & int(auyear) & ")"
Set RS = Conn.Execute(SQLStmt)
set rs=nothing
If  err.number>0 then
response.write "VBScript Errors Occured:" & "<P>"
response.write "Error Number=" & err.number & "<P>"
response.write "Error Descr.=" & err.description & "<P>"
response.write "Help Context=" & err.helpcontext & "<P>"
response.write "Help Path=" & err.helppath & "<P>"
response.write "Native Error=" & err.nativeerror & "<P>"
response.write "Source=" & err.source & "<P>"
response.write "SQLState=" & err.sqlstate & "<P>"
else
response.write "No VBScript Errors Occured" & "<P>"
end if
IF  conn.errors.count> 0 then
response.write "Database Errors Occured" & "<br>"
response.write "<b>" & SQLstmt & "</b><P>"
for counter= 0 to conn.errors.count
response.write "Error #" & conn.errors(counter).number & "<P>"
response.write "Error desc. -> " & conn.errors(counter).description & "<P>"
next
else
response.write "No Database Errors Occured!" & "<P>"
end if
Conn.Close
set conn=nothing
%>
</BODY>
</HTML>

Option 2

This page demonstrates the capabilities how to add a record to a database using ADO instead of SQL. The script is:

<html><head>
<title>dbnewrec.asp</title>&
<body bgcolor="#FFFFFF">
<% ' My ASP program that allows you to append a record %>
<form name="myauthor" action="dbnewADOrespond.asp" method="GET">
<p>Author ID: <input type="TEXT" name="id"></p>
<p> Author Name: <input type="TEXT" name="name"></p>
<p> Year Born: <input type="TEXT" name="year"></p>
<p> <input type="SUBMIT"> </p>
</form></body></html>

The form responder looks like this:

<TITLE>dbnewADO.asp</TITLE>
<body bgcolor="#FFFFFF">
<HTML>
<!--#INCLUDE VIRTUAL="/ADOVBS.INC" -->
<!--#INCLUDE VIRTUAL="/learn/test/lib_errors.asp" -->
<%
on  error resume next
auname=request.querystring("name")
auyear=request.querystring("year")
auID=request.querystring("ID")
If  auid<9000 then
auid=auid+9000
end if
conn="DSN=Student;uid=student;pwd=magic"
Set RS = Server.CreateObject("ADODB.Recordset")
RS.Open "authors",Conn,adopenstatic,adlockoptimistic
RS.AddNew
'RS("AU_ID")=auid
RS("Author") = auname
RS("Year_Born")= int(auyear)
RS.Update
Call ErrorVBscriptReport("Adding Record")
Call ErrorADOReport("Adding Record",RS.activeconnection)
RS.Close
set rs=nothing
%>
</BODY>
</HTML>