Sending file to another server using Form POST - asp-classic

I need to be able to send a file to another website from server-side Classic ASP code. The other website has a form with a file upload control, and I need to simulate posting to this form.
I found some sample code which seemed perfect for the job here, and it uploads the file without error, but the received file is not valid and when I inspect it on the other server the beginning of the file before the binary data has part of the posted data in it that shouldn't be there, eg:
ntent-Type: image/jpeg
Content-Disposition: form-data; name="file"; filename="archivebox.jpg"
ÿØÿà...
The receiving website code works fine when I upload data via a form, so it definately looks like the problem is with the above code.
If this code is not going to work, can anyone else point me in the direction of another sample for submitting files in this way?

Using the code sample in the link in my question, I modified it to build the request manually and it worked. I also converted to a single function that takes a binary file and one parameter and POSTs the request.
Function PostDocument(intDocumentID, binFile, strFilename, strContentType)
Dim objHttp, strBoundary, strRequestStart, strRequestEnd, binPost
Dim objStream
strBoundary = "---------------------------9849436581144108930470211272"
Set objHttp = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
strRequestStart = "--" & strBoundary & vbCrlf &_
"Content-Disposition: form-data; name=""id""" & vbCrlf &_
vbCrlf &_
intDocumentID & vbCrlf &_
vbCrlf &_
"--" & strBoundary & vbCrlf &_
"Content-Disposition: form-data; name=""file""; filename=""" & strFilename & """" & vbCrlf &_
"Content-Type: " & strContentType & vbCrlf &_
vbCrlf
strRequestEnd = vbCrLf & "--" & strBoundary & "--"
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Type = adTypeBinary '1
objStream.Mode = adModeReadWrite '3
objStream.Open
objStream.Write StringToBinary(strRequestStart)
objStream.Write binFile
objStream.Write StringToBinary(strRequestEnd)
objStream.Position = 0
binPost = objStream.Read
Response.Write binPost
objStream.Close
Set objStream = Nothing
objHttp.Open "POST", "(url removed)", False, "(username removed)", "(password removed)"
objHttp.setRequestHeader "Content-Type", "multipart/form-data; boundary=""" & strBoundary & """"
objHttp.Send binPost
PostDocument = objHttp.ResponseText
Set objHttp = Nothing
End Function
Function StringToBinary(toConvert)
Dim objStream, data
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Charset = "ISO-8859-1"
objStream.Type = adTypeText '2
objStream.Mode = adModeReadWrite '3
objStream.Open
objStream.WriteText toConvert
objStream.Position = 0
objStream.Type = adTypeBinary '1
StringToBinary = objStream.Read
objStream.Close
Set objStream = Nothing
End Function

Related

ASP stream send a TXT file created on the fly

I need to create and send a TXT file on the fly using classic asp. I know how to creates this file saving it into a directory and then send it using Server.CreateObject("ADODB.Stream") ... but what I wanted is to avoid saving it in the directory and just create and send on the fly.
In this case the TXT file is a list of records extracted from a MySql DB. One each line ...
strSQL = "SELECT * FROM mydb WHERE condition='ok';"
Set rs = my_conn.Execute(strSQL)
Response.Buffer = False
Dim objStream
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Type = 1 'adTypeBinary
objStream.Open
Response.ContentType = "application/x-unknown"
Response.Addheader "Content-Disposition", "attachment; filename=recordsfile.txt"
Response.BinaryWrite (dunno how to create a file with rs("field01") & " _ " & rs("field02") & vbnewline
objStream.Close
Set objStream = Nothing
Is it possible to do this ...meaning create a file in memory to strem/send ... orthere is no option but creating and saving it on disk before and send later ??
The following will work. Note: my example below assumes your recordset returns one field.
strSQL = "SELECT * FROM mydb WHERE condition='ok';"
Set rs = my_conn.Execute(strSQL)
if not rs.eof then
response.contentType = "application/octet-stream"
response.addHeader "Content-Disposition", "attachment; filename=recordsfile.txt"
do until rs.eof
response.write rs(0).value & vbcrlf
rs.movenext
loop
end if

check http connection vbscript

I need to check http connection with vbscript
I thought to ping to the host and to see if the host responds
I need to test the connection to a specific port and why not also with a url
do you have a solution?
You can try like this :
Option Explicit
Dim Title,strHost
Title = "Check Connection"
strHost = "www.stackoverflow.com"
if Ping(strHost) = True then
MsgBox "Host " & DblQuote(strHost) & " contacted",vbInformation,Title
Else
MsgBox "Host " & DblQuote(strHost) & " could not be contacted",vbCritical,Title
end if
'***********************************************************************************
Function Ping(strHost)
dim objPing, objRetStatus
set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery _
("select * from Win32_PingStatus where address = '" & strHost & "'")
for each objRetStatus in objPing
if IsNull(objRetStatus.StatusCode) or objRetStatus.StatusCode <> 0 then
Ping = False
'WScript.Echo "Status code is " & objRetStatus.StatusCode
else
Ping = True
'Wscript.Echo "Bytes = " & vbTab & objRetStatus.BufferSize
'Wscript.Echo "Time (ms) = " & vbTab & objRetStatus.ResponseTime
'Wscript.Echo "TTL (s) = " & vbTab & objRetStatus.ResponseTimeToLive
end if
next
End Function
'***********************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'************************************************************************************
I'm inspired by this ==> How to check Network port access and display useful message?
And i created a vbscript wrapped with the powershell script
Just give a try :
Option Explicit
Dim Title,Ws,ByPassPSFile,strHost,Example,PSFile,MyCmd,Result,MyArray,LogFile,fso
Title = "Check Network port access "
Set Ws = CreateObject("wscript.Shell")
Set fso = Createobject("Scripting.FileSystemObject")
LogFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "txt"
PSFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
ByPassPSFile = "cmd /c PowerShell.exe -ExecutionPolicy bypass -noprofile -file "
Example = "www.google.com:80"
strHost = InputBox("Enter the host name with its port to check it " & vbcr & "Example : " & vbcr & Dblquote(Example) & "",Title,Example)
If strHost = "" or IsEmpty(strHost) Then Wscript.Quit()
MyArray = Split(strHost,":")
MyCmd = "function Test-Port($hostname,$port)"& VbCrLF &_
"{"& VbCrLF &_
"# This works no matter in which form we get $host - hostname or ip address" & VbCrLF &_
"try {"& VbCrLF &_
"$ip = [System.Net.Dns]::GetHostAddresses($hostname) |"& VbCrLF &_
"select-object IPAddressToString -expandproperty IPAddressToString"& VbCrLF &_
"if($ip.GetType().Name -eq ""Object[]"")"& VbCrLF &_
"{"& VbCrLF &_
"#If we have several ip's for that address, let's take first one"& VbCrLF &_
"$ip = $ip[0]"& VbCrLF &_
"}"& VbCrLF &_
"} catch {"& VbCrLF &_
"return ""Possibly $hostname is wrong hostname or IP"""& VbCrLF &_
"}"& VbCrLF &_
"$t = New-Object Net.Sockets.TcpClient"& VbCrLF &_
"# We use Try\Catch to remove exception info from console if we can't connect"& VbCrLF &_
"try"& VbCrLF &_
"{"& VbCrLF &_
"$t.Connect($ip,$port)"& VbCrLF &_
"} catch {}"& VbCrLF &_
"if($t.Connected)"& VbCrLF &_
"{"& VbCrLF &_
"$t.Close()"& VbCrLF &_
"$msg = ""Port $port is operational on $hostname with ip adress $ip"""& VbCrLF &_
"}"& VbCrLF &_
"else"& VbCrLF &_
"{"& VbCrLF &_
"$msg = ""Port $port on $hostname with ip $ip is closed, """& VbCrLF &_
"$msg += ""You may need to contact your IT team to open it."""& VbCrLF &_
"}"& VbCrLF &_
"return $msg"& VbCrLF &_
"}"& VbCrLF &_
"Test-Port "& MyArray(0) & " "& MyArray(1) & " > "& LogFile &""& VbCrLF
Call WriteMyPSFile(MyCmd)
Result = Ws.run(ByPassPSFile & PSFile,0,True)
ws.run LogFile
'**********************************************************************************************
Sub WriteMyPSFile(strText)
Dim fs,ts,PSFile
Const ForWriting = 2
PSFile = Left(Wscript.ScriptFullName, InstrRev(Wscript.ScriptFullName, ".")) & "ps1"
Set fs = CreateObject("Scripting.FileSystemObject")
Set ts = fs.OpenTextFile(PSFile,ForWriting,True)
ts.WriteLine strText
ts.Close
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************

asp contact form not send to email

Hi im doing a ASP contact form and for some reason i keep getting this.
Server object error 'ASP 0177 : 800401f3'
Server.CreateObject Failed
/confirmation.asp, line 10
800401f3
I think that theres something wrong with my SMTP, please any help would be grateful.
<%
DIM strEmail, strFirstName, strLastName, strSubject, strComments
strEmail = request.form("Email")
strFirstName = request.form("FirstName")
strLastName = request.form("LastName")
strSubject = request.form("Subject")
strComments = request.form("Comments")
DIM Mailer,strMsgHeader, qryItem, strMsgInfo
Set Mailer = Server.CreateObject("smtpout.secureserver.net")//this line might be wrong.
Mailer.FromName = "Web Designs"
Mailer.FromAddress= "carlos#example.net"
Mailer.ReplyTo = strEmail
Mailer.RemoteHost = "mail.example.net"
Mailer.AddRecipient "", ""
Mailer.Subject = "Online Inquiry"
strMsgHeader = "This mail message was sent from the Online Form" & vbCrLf & vbCrLf
Mailer.BodyText = strMsgHeader & vbCrLf & "Email: " & Request.Form("Email") & _
vbCrLf & "First Name: " & Request.Form("FirstName") & _
vbCrLf & "Last Name: " & Request.Form("LastName") & _
vbCrLf & "Subject: " & Request.Form("Subject") & _
vbCrLf & "Comments: " & Request.Form("Comments")
IF Mailer.SendMail THEN
Response.Write strFirstName & ",<br>"
Response.Write "Your message has been successfully sent."
ELSE
Response.Write "The following error occurred while sending your message: " & Mailer.Response
END IF
%>
It seems you mix up the 'send email library' and your SMTP configuration.
the Mailer should look like
Set Mailer = Server.CreateObject("CDO.Message")
(although this could depend on your IIS version)
To configure your SMTP you should use this object:
Set cdoConfig = CreateObject("CDO.Configuration")
cdoConfig.Fields.Item(cdoSMTPServer) = "smtpout.secureserver.net"
Edit: example code: CDO Classic ASP form not working

Asp Classic Write PDf and keep filename when printed

I'm trying to write a pdf file to the browser and when the client print the pdf the filename sent to the printer is the name of the file. But now i'm getting the name of the asp page sent to the browser "loadfile.asp"
Because I can't put a title in my page when i'm using Response.ContentType = "application/pdf", I've added a page that do a server.Transfer.
But everytime the code pass trought the Response.ContentType = "application/pdf" the title get blanked.
So here's my code :
First Page :
<html>
<head>
<title>
<%= Request.QueryString("File") & ".PDF" %>
</title>
</head>
<body>
<%
Server.Transfer "loadfileAfter.asp"
%>
</body>
</html>
Here's the Second Page (loadfileAfter.asp) :
Response.ContentType = "application/pdf"
Response.AddHeader "content-disposition", "Filename=" & Request.QueryString("File") & ".PDF"
Const adTypeBinary = 1
strFilePath = "D:\" & Request.QueryString("File") & ".PDF" 'This is the path to the file on disk.
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Type = adTypeBinary
objStream.LoadFromFile strFilePath
Response.BinaryWrite objStream.Read
objStream.Close
Set objStream = Nothing
I tought that this line would help :
Response.AddHeader "content-disposition", "Filename=" & Request.QueryString("File") & ".PDF"
But it did not change a thing.
Thanks for your help
This one worked for me:
Response.AddHeader "content-disposition", "attachment; filename=""" & fileName & """"

RestSharp in Visual basic 6

I have this code in Visual Basic .net and I would like to make the same thing in Visual Basic 6. The code upload an image to a given URL. I have to use Rest protocol because the server I upload the image request it.
Dim res As New RestSharp.RestRequest("URL_OF_SERVER", RestSharp.Method.POST)
res.AddFile("file", "File_location_on_PC")
Dim restClient As New RestSharp.RestClient()
Dim r As New RestSharp.RestResponse
r = restClient.Execute(res)
Is it posible to do the same Rest Protocol in Visual Basic 6?
EDIT 1: I HAVE TRIED THIS BUT AN ERROR HAPPENS
Dim xmlhttp As MSXML2.XMLHTTP30
Const STR_BOUNDARY As String = "3fbd04f5-b1ed-4060-99b9-fca7ff59c113"
Dim nFile As Integer
Dim baBuffer() As Byte
Dim sPostData As String
'--- read file
nFile = FreeFile
Open NombreArchivo For Binary Access Read As nFile
If LOF(nFile) > 0 Then
ReDim baBuffer(0 To LOF(nFile) - 1) As Byte
Get nFile, , baBuffer
sPostData = StrConv(baBuffer, vbUnicode)
End If
Close nFile
'--- prepare body
sPostData = "--" & STR_BOUNDARY & vbCrLf & _
" Content-Disposition: form-data; name=""image002""; filename=""C:\image002.jpg" & _
"--" & STR_BOUNDARY & "--"
'--- post
Set xmlhttp = New MSXML2.XMLHTTP30
With xmlhttp
.Open "POST", Url, False
.setRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY
.send pvToByteArray(sPostData)
End With
Private Function pvToByteArray(sText As String) As Byte()
pvToByteArray = StrConv(sText, vbFromUnicode)
End Function
ERROR :
responseText
{"message":"file.not_found","error":"There is no file in request.","status":400,"cause":[]}
Thanks!
If you need just to post a file here is a simple function
Private Sub pvPostFile(sUrl As String, sFileName As String, Optional ByVal bAsync As Boolean)
Const STR_BOUNDARY As String = "3fbd04f5-b1ed-4060-99b9-fca7ff59c113"
Dim nFile As Integer
Dim baBuffer() As Byte
Dim sPostData As String
'--- read file
nFile = FreeFile
Open sFileName For Binary Access Read As nFile
If LOF(nFile) > 0 Then
ReDim baBuffer(0 To LOF(nFile) - 1) As Byte
Get nFile, , baBuffer
sPostData = StrConv(baBuffer, vbUnicode)
End If
Close nFile
'--- prepare body
sPostData = "--" & STR_BOUNDARY & vbCrLf & _
"Content-Disposition: form-data; name=""uploadfile""; filename=""" & Mid$(sFileName, InStrRev(sFileName, "\") + 1) & """" & vbCrLf & _
"Content-Type: application/octet-stream" & vbCrLf & vbCrLf & _
sPostData & vbCrLf & _
"--" & STR_BOUNDARY & "--"
'--- post
With CreateObject("Microsoft.XMLHTTP")
.Open "POST", sUrl, bAsync
.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" & STR_BOUNDARY
.Send pvToByteArray(sPostData)
End With
End Sub
Private Function pvToByteArray(sText As String) As Byte()
pvToByteArray = StrConv(sText, vbFromUnicode)
End Function
You can switch to MSXML2.ServerXMLHTTP to be able to use its SetTimeouts method if your file is large enough and timeouts in 30 sec.
You can create a COM callable wrapper (CCW) for the RestSharp assembly - see this URL for details of how to do this:
http://msdn.microsoft.com/en-us/library/ms973802.aspx
Once it is registered, you can use RestSharp from VB6.

Resources