Save a <canvas> as a file in a form - forms

Using Canvas method toDataURL, I would like to be able to save the image on the server side (using Rails).
With toDataURL string, how to use it in a form that can be seen as a file attachment in a HTML form ?

Solution using jQuery, Paperclip, datafy.rb
http://gist.github.com/397615

Here is my solution:
The problem: Compact uploaded images of any size before sending it to the server, which will save the image.
Files involved: 2 ASP pages: one that will act client-side and another server-side.
The Presentation page:
<html>
<!-- by arturmariojr#gmail.com - on december/2012 -->
<script language='javaScript'>
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Great success! All the File APIs are supported.
} else {
alert('Este Browser não suporte a API Files');
}
function Compactar(Elemento) {
var file = document.getElementById(Elemento),
reader = new FileReader(), // métodos assíncronos, por isso os eventos!
form = document.getElementById('frmFotos');
//alert(file.id);
reader.readAsDataURL(file.files[0]); // aqui a abertura do arquivo, que irá disparar a função acima
reader.onloadend = function() { // aqui um evento, que será disparado na primeira linha abaixo da função chamada
var image = new Image();
image.src = reader.result; // vai disparar o tratamento do evento abaixo
image.onload = function() {
var maxWidth = 800,
maxHeight = 600,
width = image.width,
height = image.height;
// calculate the width and height, constraining the proportions
if (width > height) {
if (width > maxWidth) {
//height *= max_width / width;
height = Math.round(height *= maxWidth / width);
width = maxWidth;
}
} else {
if (height > maxHeight) {
//width *= max_height / height;
width = Math.round(width *= maxHeight / height);
height = maxHeight;
}
}
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(image, 0, 0, maxWidth, maxHeight);
// The resized file ready for upload
var finalFile = canvas.toDataURL("image/jpeg",0.8); //a 80% de qualidade
// aqui cria-se novo input comun!
/*var newinput = document.createElement("input");
newinput.type = 'text';
newinput.name = "edt" & Elemento;
newinput.value = finalFile; // put result from canvas into new hidden input
form.appendChild(newinput);*/
document.getElementById("edtArq_1").value = finalFile;
var preview = document.getElementById('preview');
//alert(preview.id);
preview.appendChild(canvas); // do the actual resized preview
}
}
}
</script>
<html>
<form id="form" action="submit" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<!-- this will be left behind - we don't want to upload Mbytes of information -->
<input type='file' name='Arq_1' id='Arq_1' size='50' onchange='Compactar("Arq_1");'>
<form method="POST" id='frmFotos' action='SalvaArquivo.asp'>
<!-- this could be a hidden element -->
<input name='edtArq_1' id='edtArq_1'><br>
<input type='submit' name ='cmdEnviar' id='cmdEnviar' value='Enviar' >
</form>
<!-- just for you see the new resized image - no upload too -->
<div id="preview"></div>
</html>
The page that will reveive the request from the first page and save the image:
<html>
<!-- by arturmariojr#gmail.com - on december/2012 -->
<!-- this script could be avoided if I had put the img element in the page directly
. By the way, actualyy there's no necessity of showing nothing to user
-->
<script language='JavaScript'>
var newImg = document.createElement("img");
newImg.src = '<%=request.form("edtArq_1")%>';
document.body.appendChild(newImg);
</script>
<body>
<input name='edtOriginal' value='<%=request.form("edtArq_1")%>'>
<%
' the data is encoded, so, we will need to deencode it ...
Function Base64Decode(ByVal base64String)
'rfc1521
'1999 Antonin Foller, Motobit Software, http://Motobit.cz
Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Dim dataLength, sOut, groupBegin
'remove white spaces, If any
base64String = Replace(base64String, vbCrLf, "")
base64String = Replace(base64String, vbTab, "")
base64String = Replace(base64String, " ", "")
'The source must consists from groups with Len of 4 chars
dataLength = Len(base64String)
If dataLength Mod 4 <> 0 Then
Err.Raise 1, "Base64Decode", "Bad Base64 string."
Exit Function
End If
' Now decode each group:
For groupBegin = 1 To dataLength Step 4
Dim numDataBytes, CharCounter, thisChar, thisData, nGroup, pOut
' Each data group encodes up To 3 actual bytes.
numDataBytes = 3
nGroup = 0
For CharCounter = 0 To 3
' Convert each character into 6 bits of data, And add it To
' an integer For temporary storage. If a character is a '=', there
' is one fewer data byte. (There can only be a maximum of 2 '=' In
' the whole string.)
thisChar = Mid(base64String, groupBegin + CharCounter, 1)
If thisChar = "=" Then
numDataBytes = numDataBytes - 1
thisData = 0
Else
thisData = InStr(1, Base64, thisChar, vbBinaryCompare) - 1
End If
If thisData = -1 Then
Err.Raise 2, "Base64Decode", "Bad character In Base64 string."
Exit Function
End If
nGroup = 64 * nGroup + thisData
Next
'Hex splits the long To 6 groups with 4 bits
nGroup = Hex(nGroup)
'Add leading zeros
nGroup = String(6 - Len(nGroup), "0") & nGroup
'Convert the 3 byte hex integer (6 chars) To 3 characters
pOut = Chr(CByte("&H" & Mid(nGroup, 1, 2))) + _
Chr(CByte("&H" & Mid(nGroup, 3, 2))) + _
Chr(CByte("&H" & Mid(nGroup, 5, 2)))
'add numDataBytes characters To out string
sOut = sOut & Left(pOut, numDataBytes)
Next
Base64Decode = sOut
End Function
' now, we will save the data (new image) using the old FileSystemObject !!!
Set fso = Server.CreateObject ("Scripting.FileSystemObject")
If Err.Number <> 0 Then
Response.write "Não foi possível instanciar objeto fso!<br>" & Err.description
response.end
End if
dim Caminho, objArq
Caminho = Server.MapPath("./images") 'where I saved the new image
response.write Caminho
If Err.Number <> 0 Then
Response.write "Não foi possível localizar caminho! " & Caminho & "<br>" & Err.description & "<br>"
else
Set oFile = fso.CreateTextFile(Caminho & "\Teste.jpg", true)
oFile.Write Base64Decode(replace(request.form("edtArq_1"), "data:image/jpeg;base64,", "")) 'BinaryToString(request.from("edtArq_1"))
If Err.Number <> 0 Then
Response.write "Não foi possível localizar thum(s)!" & Caminho & "<br>" & Err.description & "<br>"
end if
oFile.close
end if
%>
</body>
</html>

Related

Using multipart/form-data in Windows metro apps

I'm trying to create a way to upload text data (database key) along with an .png image from a Windows 8.1 App, through a multipart/form-data HTTP POST request, to a PHP script hosted on a webserver (which saves the image locally using the database key as a filename)
I've had a look at packet sniffer and it's all coming out the way I think it should, but the problem is that the PHP $_POST value is not passing through and is null on the php script side.
Here is the C# code on the Windows Metro app side:
private async void UploadImage() {
string newLine = Environment.NewLine;
WebRequest request = WebRequest.Create("http://www.mywebsite.com/receiveimage.php");
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "POST";
string boundary = "---------------------BUIUFBILPQMZ81C12CCC2EVV2RJ";
request.ContentType = "multipart/form-data; boundary=" + boundary;
// Open pre-saved MY_FILE.png file from local disk and store in fh
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile fh = await localFolder.GetFileAsync("MY_FILE.png");
// Header strings and values
string Prefix1 = boundary + newLine + "Content-Disposition: form-data; name=\"SERIAL_NO\"" + newLine + newLine; // SERIAL_NO is the php $_POST variable
string Prefix2 = boundary + newLine + "Content-Disposition: form-data; name=\"MY_FILE\"; filename=\"" + "MY_FILE.png\"" + newLine + "Content-Type: application/base64" + newLine + newLine;
byte[] baPrefix1 = System.Text.Encoding.UTF8.GetBytes(Prefix1);
byte[] baValue1 = System.Text.Encoding.UTF8.GetBytes("C4145-12" + newLine); // (C4145-12 is the database key)
IBuffer buffer = await FileIO.ReadBufferAsync(fh);
byte[] baPrefix2 = System.Text.Encoding.UTF8.GetBytes(Prefix1);
byte[] baValue2 = System.Text.Encoding.UTF8.GetBytes(System.Convert.ToBase64String(buffer.ToArray()).Replace("+", "%2B") + newLine);
byte[] combinedData = new byte[baPrefix1.Length + baValue1.Length + baPrefix2.Length + baValue2.Length];
System.Buffer.BlockCopy(baPrefix1, 0, combinedData, 0, baPrefix1.Length);
System.Buffer.BlockCopy(baValue1, 0, combinedData, baPrefix1.Length, baValue1.Length);
System.Buffer.BlockCopy(baPrefix2, 0, combinedData, baPrefix1.Length + baValue1.Length, baPrefix2.Length);
System.Buffer.BlockCopy(baValue2, 0, combinedData, baPrefix1.Length + baValue1.Length + baPrefix2.Length, baValue2.Length);
Stream dataStream = await request.GetRequestStreamAsync();
dataStream.Write(combinedData, 0, combinedData.Length);
dataStream.Dispose();
using (WebResponse response = await request.GetResponseAsync())
{
// "STATUS" is just a text block
STATUS.Text = (((HttpWebResponse)response).StatusDescription);
StreamReader reader = new StreamReader(response.GetResponseStream());
string responseFromServer = reader.ReadToEnd();
STATUS.Text = responseFromServer;
}
}
The PHP script on the server works with other forms but can't recognize the value passed in from this script, so I know it's not an issue with that. I'm convinced it's a problem with the header formatting. I've experimented with the amount of new lines but to no avail. Any ideas?

How to send outlook mails without opening outlook in PC by testcomplete

i am trying to send outlook mail using vb script language in testcomplete. i am able to send but if the outlook is opened in my PC then only mail will be sent and if the oulook is not opened in my pc,my mail will not be sent untill opening the outllok even after executing this script
here is my code:
Function SendMail
Dim objOutLook, NamespaceMAPI,objNewMail, fso, SendReceiveControls
Dim strTo,strCc ,strBcc ,strSubject, AccountName,strAttachmentPath
strSubject="test"
strTo=yyy#yy.com
strCc=XXX#XX.com
strBcc =zzz#zzz.com
strAttachmentPath="c:\text.txt"
If strTo ="" and strCc = "" and strBcc =""Then
Exit function
ElseIf strSubject =""Then
Exit function
End If
Set objOutLook = CreateObject("Outlook.Application")
Set NamespaceMAPI = objOutLook.GetNamespace("MAPI")
Set objNewMail = objOutLook.CreateItem(olMailItem)
objOutLook.DisplayAlerts =True
objNewMail.TO = strTo
objNewMail.CC = strCc
objNewMail.BCC=strBcc
objNewMail.Subject = strSubject
objNewMail.Body = strMsg
If strAttachmentPath <> "" Then
Set fso =CreateObject("Scripting.FileSystemObject")
If fso.FileExists(strAttachmentPath) Then
objNewMail.Attachments.Add(strAttachmentPath)
objNewMail.display
Else
msgbox "Attachment File Does not exists"
End If
End If
AccountName="XXXXXX#XXXX.com"
' Finding the "Send/Receive" control
Set SendReceiveControls = NamespaceMAPI.GetDefaultFolder("Inbox")._
CommandBars("STANDARD").Controls("Send/Receive")
Set Item = Nothing
'msgbox "send:"&SendReceiveControls.Controls.Count
For I = 1 To SendReceiveControls.Controls.Count
If InStr(SendReceiveControls.Controls(I).Caption, AccountName) > 0 Then
Set Item = SendReceiveControls.Controls(I)
'msgbox "send1"&SendReceiveControls.Controls(I)
Exit For
End If
Next
' Executing the "Send/Receive" action
Item.Controls(1).Execute()
objOutLook.Quit
''''''' Releasing objects '''''''
Set objOutLook =Nothing
Set objNewMail = Nothing
Set fso = Nothing
End Function
please suggest me how to handle this...thanks in advance
Do you really need to send it with outlook?
I use this javascript code to send the email, then, in outlook, you just need to mark it as not spam, otherwise, it goes directly to the spam inbox
function SendEmail(mFrom, mTo, mSubject, mBody, username, password)
{
var i, schema, mConfig, mMessage;
try
{
schema = "http://schemas.microsoft.com/cdo/configuration/";
mConfig = Sys.OleObject("CDO.Configuration");
mConfig.Fields.Item(schema + "sendusing") = 2; // cdoSendUsingExchange
mConfig.Fields.Item(schema + "smtpserver") = "STMP SERVER ADDRESS HERE"; // SMTP server
mConfig.Fields.Item(schema + "smtpserverport") = 25; // Port number
mConfig.Fields.Item(schema + "smtpauthenticate") = 1; // Authentication mechanism
mConfig.Fields.Item(schema + "sendusername") = username; // User name (if needed)
mConfig.Fields.Item(schema + "sendpassword") = password; // User password (if needed)
mConfig.Fields.Update();
mMessage = Sys.OleObject("CDO.Message");
mMessage.Configuration = mConfig;
mMessage.From = mFrom;
mMessage.To = mTo;
mMessage.Subject = mSubject;
mMessage.HTMLBody = mBody;
mMessage.Send();
}
catch (exception)
{
Log.Error("E-mail cannot be sent", exception.description);
return false;
}
Log.Message("Message to <" + mTo + "> was successfully sent");
return true;
}
Try objNewMail.Body.Send instead of trying to execute the send and receive button. Here's a simple example:
Function SendMail()
Dim objOutlook, objNewMail
Set objOutLook = CreateObject("Outlook.Application")
Set objNewMail = objOutLook.CreateItem(olMailItem)
objNewMail.TO = "myrecip#test.com"
objNewMail.Subject = "test"
objNewMail.Body = "test"
objNewMail.Send
End Function

Qlikview Macro VBScript to print pdf and email will not run consistently - Fails in email

I have been tearing my hair out over the last few days in trying to get this macro to work consistantly on the Windows scheduler.
Basically the workflow is as follows:
1) Windows Scheduler - Daily, uses Admin user credentials
2) Batch file - Reloads using /l
3) Reloads Qlikview application, which has triggers on post reload to save a pdf and email it using PDF Xchange and an html formatted e-mail to cover mobile.
I am getting such inconsistent behaviour that I cannot isolate the problem to any particular one thing. Sometimes it works, sometimes it doesn't. More often than not it fails on the Windows scheduler. There is no error since QV has just thrown up the VBScript window in the hidden process.
I've been changing permissions, which helped me reach a level of inconsistent performance as opposed to no performance.
In addition, it appears that you cannot pass variables to the PDF Xchange printer.
The code in the macro is as follows:
sub ExportPDF
printReportPDF "\\SGH-SRV-FPS1\S-Drive\eCommerce\Data Analyst\Reporting\Daily E-Commerce Report\E-Commerce Daily Report.pdf"
ActiveDocument.GetApplication.Sleep 2000
ActiveDocument.PrintReport "RP01", "PDF-XChange 3.0"
ActiveDocument.GetApplication.Sleep 8000
end sub
Function printReportPDF(pdfOutputFile)
Set WSHShell = CreateObject("WScript.Shell")
WSHShell.RegWrite "HKCU\Software\Tracker Software\PDF-XChange 3.0\OutputFile", pdfOutputFile, "REG_SZ"
WSHShell.RegWrite "HKCU\Software\Tracker Software\PDF-XChange 3.0\BypassSaveAs", "1", "REG_SZ"
Set WSHShell = nothing
End function
Sub ExportEmail
Dim strvDest 'as string
strvDest = ActiveDocument.Variables("vDestination").GetContent().String
msgbox(strvDestination)
Define report variables
get the date as a serial for the filename output
Export an Object
Set obj = ActiveDocument.ActiveSheet.SheetObjects("TX25")
Set obj1 = ActiveDocument.ActiveSheet.SheetObjects("TX17")
Set obj2 = ActiveDocument.ActiveSheet.SheetObjects("TX18")
Set obj3 = ActiveDocument.ActiveSheet.SheetObjects("TX15")
Set obj5 = ActiveDocument.ActiveSheet.SheetObjects("CH62")
Set obj6 = ActiveDocument.ActiveSheet.SheetObjects("TX16")
Set obj8 = ActiveDocument.ActiveSheet.SheetObjects("CH58")
Set obj9 = ActiveDocument.ActiveSheet.SheetObjects("TX31")
Set obj10 = ActiveDocument.ActiveSheet.SheetObjects("CH69")
msgbox("defined objects")
obj.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainLogo.jpg"
obj1.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainHeader.jpg"
obj2.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\DateRange.jpg"
obj3.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader.jpg"
obj5.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\DailySiteDetail.jpg"
obj6.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader2.jpg"
obj8.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetail.jpg"
obj9.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader3.jpg"
obj10.ExportBitmapToFile "D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetailLW.jpg"
msgbox("created objects")
Dim objEmail
Const cdoSendUsingPort = 2 Send the message using SMTP
Const cdoAnonymous = 0 Do not authenticate
Const cdoBasic = 1 basic (clear-text) authentication
Const cdoNTLM = 2 NTLM
Const SMTPServer = "xxxx" ' changed for public consumption
Const SMTPPort = 25 ' Port number for SMTP
Const SMTPTimeout = 120 ' Timeout for SMTP in seconds
Set objEmail = CreateObject("CDO.Message")
Set objConf = objEmail.Configuration
Set objFlds = objConf.Fields
With objFlds
———————————————————————
SMTP server details
removed the html links down to this being my first post
.Update
———————————————————————
End With
allow the passing of a variable from the load script to define the distribution list
if len(strvDest) > 0 then
msgbox("variable exists "&strvDest)
objEmail.To = strvDest
else
msgbox("variable does not exist")
objEmail.To = "xxxx" 'changed for public consumption
end if
objEmail.From = "xxxx" 'changed for public consumption
objEmail.Subject = "Daily Reporting"
HTML = "<!DOCTYPE HTML PUBLIC ""-//IETF//DTD HTML//EN"">" & chr(13) & chr(10)
HTML = HTML & "<html>"
HTML = HTML & "<head>"
HTML = HTML & "<meta http-equiv=""Content-Type"" content=""text/html; charset=iso-8859-1"">"
HTML = HTML & "<title>Automated Emails!</title>"
HTML = HTML & "</head>"
HTML = HTML & "<body bgcolor=""#FFFFFF"">"
HTML = HTML & "<br> <img src=""cid:MainLogo.jpg"" >"
HTML = HTML & "<br> <img src=""cid:MainHeader.jpg"" >"
HTML = HTML & "<br> <img src=""cid:DateRange.jpg"" >"
HTML = HTML & "<br> <img src=""cid:SecondaryHeader.jpg"" >"
HTML = HTML & "<br> <img src=""cid:DailySiteDetail.jpg"" >"
HTML = HTML & "<br> <img src=""cid:SecondaryHeader2.jpg"" >"
HTML = HTML & "<br> <img src=""cid:WeeklySiteDetail.jpg"" >"
HTML = HTML & "<br> <img src=""cid:SecondaryHeader3.jpg"" >"
HTML = HTML & "<br> <img src=""cid:WeeklySiteDetailLW.jpg"" >"
HTML = HTML & "<p>"
HTML = HTML & "</p>"
HTML = HTML & "</body>"
HTML = HTML & "</html>"
Set objBP = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainLogo.jpg", "MainLogo.jpg", CdoReferenceTypeName)
objBP.Fields.Item("urn:schemas:mailheader:Content-ID") = "<MainLogo.jpg>"
objBP.Fields.Update
Set objBP1 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\MainHeader.jpg", "MainHeader.jpg", CdoReferenceTypeName)
objBP1.Fields.Item("urn:schemas:mailheader:Content-ID") = "<MainHeader.jpg>"
objBP1.Fields.Update
Set objBP2 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\DateRange.jpg", "DateRange.jpg", CdoReferenceTypeName)
objBP2.Fields.Item("urn:schemas:mailheader:Content-ID") = "<DateRange.jpg>"
objBP2.Fields.Update
Set objBP3 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader.jpg", "SecondaryHeader.jpg", CdoReferenceTypeName)
objBP3.Fields.Item("urn:schemas:mailheader:Content-ID") = "<SecondaryHeader.jpg>"
objBP3.Fields.Update
Set objBP5 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\DailySiteDetail.jpg", "DailySiteDetail.jpg", CdoReferenceTypeName)
objBP5.Fields.Item("urn:schemas:mailheader:Content-ID") = "<DailySiteDetail.jpg>"
objBP5.Fields.Update
Set objBP6 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader2.jpg", "SecondaryHeader2.jpg", CdoReferenceTypeName)
objBP6.Fields.Item("urn:schemas:mailheader:Content-ID") = "<SecondaryHeader2.jpg>"
objBP6.Fields.Update
Set objBP8 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetail.jpg", "WeeklySiteDetail.jpg", CdoReferenceTypeName)
objBP8.Fields.Item("urn:schemas:mailheader:Content-ID") = "<WeeklySiteDetail.jpg>"
objBP8.Fields.Update
Set objBP9 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\SecondaryHeader3.jpg", "SecondaryHeader3.jpg", CdoReferenceTypeName)
objBP9.Fields.Item("urn:schemas:mailheader:Content-ID") = "<SecondaryHeader3.jpg>"
objBP9.Fields.Update
Set objBP10 = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\WeeklySiteDetailLW.jpg", "WeeklySiteDetailLW.jpg", CdoReferenceTypeName)
objBP10.Fields.Item("urn:schemas:mailheader:Content-ID") = "<WeeklySiteDetailLW.jpg>"
objBP10.Fields.Update
Set objBPDoc = objEmail.AddRelatedBodyPart("D:\QlikView\SGP-UDA\QVS_Source\UserApp\Qlikview Printing.pdf", "Qlikview Printing.pdf", CdoReferenceTypeName)
objBPDoc.Fields.Item("urn:schemas:mailheader:Content-ID") = "<Qlikview Printing.pdf>"
objBPDoc.Fields.Update
objEmail.HTMLBody = HTML
msgbox("attached objects")
objEmail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objEmail = Nothing
ActiveDocument.Save
Application.Quit
End Sub
I cannot ask questions so I will try to give you an answer of the bat.
Firstly, does it reload manually from the QV Document? If yes then
Then you are most probably using 2 differant usernames to reload, please make sure that the username used to reload via scheduler has permissions on every single file the VB is accessing.
Did you set the permissions on the VB side to the following:
Requested Module Security = System Access
Current Local Security = Allow system access
Lastly, On the General screen of the scheduled task, under security options at the bottom. Make sure "Run with highest privileges" is unticked, this sometimes causes issues.

How to Insert Record and Upload file using the FreeASPUpload Script

I want to Insert record and upload file at the same time, right now im using FreeASPUpload Script. When i submit the form it returns this error
Cannot use the generic Request collection after calling BinaryRead
Here is the Full Source Code of my page
<%
option explicit
Response.Expires = -1
Server.ScriptTimeout = 600
Session.CodePage = 65001
%>
<!-- #include file="UploadClass.asp" -->
<%
Dim uploadsDirVar
uploadsDirVar = server.MapPath("Files_Uploaded")
function OutputForm()
%>
<form name="frmSend" method="POST" enctype="multipart/form-data" accept-charset="utf-8" action="form.asp" onSubmit="return onSubmitForm();">
<input type="hidden" name="ApplicationForm" value="Insert" />
Name: <input type="text" name="name_insert" value="" size="30" />
<B>File names:</B><br>
File 1: <input name="attach1" type="file" size=35><br>
<br>
<input style="margin-top:4" type="submit" value="Submit">
</form>
<%
end function
function TestEnvironment()
Dim fso, fileName, testFile, streamTest
TestEnvironment = ""
Set fso = Server.CreateObject("Scripting.FileSystemObject")
if not fso.FolderExists(uploadsDirVar) then
TestEnvironment = "<B>Folder " & uploadsDirVar & " does not exist.</B><br>The value of your uploadsDirVar is incorrect. Open uploadTester.asp in an editor and change the value of uploadsDirVar to the pathname of a directory with write permissions."
exit function
end if
fileName = uploadsDirVar & "\test.txt"
on error resume next
Set testFile = fso.CreateTextFile(fileName, true)
If Err.Number<>0 then
TestEnvironment = "<B>Folder " & uploadsDirVar & " does not have write permissions.</B><br>The value of your uploadsDirVar is incorrect. Open uploadTester.asp in an editor and change the value of uploadsDirVar to the pathname of a directory with write permissions."
exit function
end if
Err.Clear
testFile.Close
fso.DeleteFile(fileName)
If Err.Number<>0 then
TestEnvironment = "<B>Folder " & uploadsDirVar & " does not have delete permissions</B>, although it does have write permissions.<br>Change the permissions for IUSR_<I>computername</I> on this folder."
exit function
end if
Err.Clear
Set streamTest = Server.CreateObject("ADODB.Stream")
If Err.Number<>0 then
TestEnvironment = "<B>The ADODB object <I>Stream</I> is not available in your server.</B><br>Check the Requirements page for information about upgrading your ADODB libraries."
exit function
end if
Set streamTest = Nothing
end function
function SaveFiles
Dim Upload, fileName, fileSize, ks, i, fileKey
Set Upload = New FreeASPUpload
Upload.Save(uploadsDirVar)
' If something fails inside the script, but the exception is handled
If Err.Number<>0 then Exit function
SaveFiles = ""
ks = Upload.UploadedFiles.keys
if (UBound(ks) <> -1) then
SaveFiles = "<B>Files uploaded:</B> "
for each fileKey in Upload.UploadedFiles.keys
SaveFiles = SaveFiles & Upload.UploadedFiles(fileKey).FileName & " (" & Upload.UploadedFiles(fileKey).Length & "B) "
next
else
SaveFiles = "No file selected for upload or the file name specified in the upload form does not correspond to a valid file in the system."
end if
SaveFiles = SaveFiles & "<br>Enter a number = " & Upload.Form("enter_a_number") & "<br>"
SaveFiles = SaveFiles & "Checkbox values = " & Upload.Form("checkbox_values") & "<br>"
SaveFiles = SaveFiles & "List values = " & Upload.Form("list_values") & "<br>"
SaveFiles = SaveFiles & "Text area = " & Upload.Form("t_area") & "<br>"
end function
%>
<HTML>
<HEAD>
<TITLE>Test Free ASP Upload 2.0</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
BODY {background-color: white;font-family:arial; font-size:12}
</style>
<script>
function onSubmitForm() {
var formDOMObj = document.frmSend;
if (formDOMObj.attach1.value == "")
alert("Please press the Browse button and pick a file.")
else
return true;
return false;
}
</script>
</HEAD>
<BODY>
<br><br>
<div style="border-bottom: #A91905 2px solid;font-size:16">Upload files to your server</div>
<%
Dim diagnostics
if Request.ServerVariables("REQUEST_METHOD") <> "POST" then
diagnostics = TestEnvironment()
if diagnostics<>"" then
response.write "<div style=""margin-left:20; margin-top:30; margin-right:30; margin-bottom:30;"">"
response.write diagnostics
response.write "<p>After you correct this problem, reload the page."
response.write "</div>"
else
response.write "<div style=""margin-left:150"">"
OutputForm()
response.write "</div>"
end if
else
response.write "<div style=""margin-left:150"">"
OutputForm()
response.write SaveFiles()
response.write "<br><br></div>"
end if
%>
</BODY>
</HTML>
<!-- #include file="ADOVBS.inc" -->
<%
'=======================================================================================
' CONNECT DATABASE
'=======================================================================================
Dim objConn, objRs
Set objConn = CreateObject("ADODB.Connection")
Set objRs = CreateObject("ADODB.Recordset")
objConn.open"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& server.MapPath("db/Job_database.mdb") &";Mode=ReadWrite|Share Deny None;Persist Security Info=False"
If Request("ApplicationForm") = "Insert" Then
Set InsCom=Server.CreateObject("ADODB.Command")
InsCom.ActiveConnection=objConn
InsName = Trim(request("name_insert"))
InsName = replace(InsName,"'","''")
InsCom.CommandText = "Insert into applications(aname)Values(?)"
InsCom.Parameters.Append InsCom.CreateParameter("#name_insert", adVarChar, adParamInput, 255, InsName)
InsCom.Execute
End If
%>
I have been searching for this problem, but couldn't make it work. although what i found is that i have to use the Form Collection provided by FreeASPUpload. therefore i change
If Request("ApplicationForm") = "Insert" Then
to this
If Upload.Form("ApplicationForm") = "Insert" Then
But it also returns an error, that says: Variable is undefined: 'Upload'
If i change the Request method, it only Uploads the file not inserts the record
If Request.QueryString("ApplicationForm") = "Insert" Then
What i understands is that my insert query is in wrong place or so...
Please help me solve this problem.. thanks
I haven't used AspFreeUpload much so I'm guessing a bit here.
It would appear that using the Request object isn't an option so you're stuck with having to use the Upload.Form. As your code stands, the Upload object is only defined and set within the context of your SaveFiles function.
Try moving your database insert code to within the SaveFiles function. This would mean cutting everything from the line
Dim objConn, objRs
to
InsCom.Execute
and pasting it just before 'End Function'
You may also need to move your include adovbs.inc directive to somewhere before the function was called. The most logical place would be on the line immediately below your other include directive = for uploadclass.asp

Classic ASP amazon s3 rest authorisation

I am confused on what I am doing wrong here...
<script language="javascript" runat="server">
function GMTNow(){return new Date().toGMTString()}
</script>
<%
Const AWS_BUCKETNAME = "uk-bucketname"
Const AWS_ACCESSKEY = "GOES HERE"
Const AWS_SECRETKEY = "SECRET"
LocalFile = Server.Mappath("/test.jpg")
Dim sRemoteFilePath
sRemoteFilePath = "/files/test.jpg" 'Remote Path, note that AWS paths (in fact they aren't real paths) are strictly case sensitive
Dim strNow
strNow = GMTNow() ' GMT Date String
Dim StringToSign
StringToSign = Replace("PUT\n\nimage/jpeg\n\nx-amz-date:" & strNow & "\n/"& AWS_BUCKETNAME & sRemoteFilePath, "\n", vbLf)
Dim Signature
Signature = BytesToBase64(HMACSHA1(AWS_SECRETKEY, StringToSign))
Dim Authorization
Authorization = "AWS " & AWS_ACCESSKEY & ":" & Signature
Dim AWSBucketUrl
AWSBucketUrl = "http://s3.amazonaws.com/" & AWS_BUCKETNAME
With Server.CreateObject("Microsoft.XMLHTTP")
.open "PUT", AWSBucketUrl & sRemoteFilePath, False
.setRequestHeader "Authorization", Authorization
.setRequestHeader "Content-Type", "image/jpeg"
.setRequestHeader "Host", AWS_BUCKETNAME & ".s3.amazonaws.com"
.setRequestHeader "x-amz-date", strNow
.send GetBytes(LocalFile) 'Get bytes of local file and send
If .status = 200 Then ' successful
Response.Write "<a href="& AWSBucketUrl & sRemoteFilePath &" target=_blank>Uploaded File</a>"
Else ' an error ocurred, consider xml string of error details
Response.ContentType = "text/xml"
Response.Write .responseText
End If
End With
Function GetBytes(sPath)
dim fs,f
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.GetFile(sPath)
GetBytes = f.Size
set f=nothing
set fs=nothing
End Function
Function BytesToBase64(varBytes)
With Server.CreateObject("MSXML2.DomDocument").CreateElement("b64")
.dataType = "bin.base64"
.nodeTypedValue = varBytes
BytesToBase64 = .Text
End With
End Function
Function HMACSHA1(varKey, varValue)
With Server.CreateObject("System.Security.Cryptography.HMACSHA1")
.Key = UTF8Bytes(varKey)
HMACSHA1 = .ComputeHash_2(UTF8Bytes(varValue))
End With
End Function
Function UTF8Bytes(varStr)
With Server.CreateObject("System.Text.UTF8Encoding")
UTF8Bytes = .GetBytes_4(varStr)
End With
End Function
%>
Now getting the error.
msxml3.dll error '800c0008'
The download of the specified resource has failed.
/s3.asp, line 39
I'd like to explain how S3 Rest Api works as far as I know.First, you need to learn what should be the string to sign Amazon accepts.
Format :
StringToSign = HTTP-Verb + "\n" +
Content-MD5 + "\n" +
Content-Type + "\n" +
Date + "\n" +
CanonicalizedAmzHeaders +
CanonicalizedResource;
Generating signed string :
Signature = Base64( HMAC-SHA1( YourSecretAccessKeyID, UTF-8-Encoding-Of( StringToSign ) ) );
Passing authorization header:
Authorization = "AWS" + " " + AWSAccessKeyId + ":" + Signature;
Unfortunately you'll play byte to byte since there is no any SDK released for classic asp. So, should understand by reading the entire page http://docs.amazonwebservices.com/AmazonS3/latest/dev/RESTAuthentication.html
For string to sign as you can see above in format, there are three native headers are reserved by the API. Content-Type, Content-MD5 and Date. These headers must be exists in the string to sign even your request hasn't them as empty without header name, just its value. There is an exception, Date header must be empty in string to sign if x-amz-date header is already exists in the request. Then, If request has canonical amazon headers, you should add them as key-value pairs like x-amz-headername:value. But, there is another exception need to be considered for multiple headers. Multiple headers should combine to one header with values comma separated.
Correct
x-amz-headername:value1,value2
Wrong
x-amz-headername:value1\n
x-amz-headername:value2
Most importantly, headers must be ascending order by its group in the string to sign. First, reserved headers with ascending order, then canonical headers with ascending order.
I'd recommend using DomDocument functionality to generate Base64 encoded strings.
Additionally instead of a Windows Scripting Component (.wsc files), you could use .Net's interops such as System.Security.Cryptography to generating keyed hashes more effectively with power of System.Text. All of these interoperabilities are available in today's IIS web servers.
So, as an example I wrote the below script just sends a file to bucket you specified. Consider and test it.
Assumed local file name is myimage.jpg and will be uploaded with same name to root of the bucket.
<script language="javascript" runat="server">
function GMTNow(){return new Date().toGMTString()}
</script>
<%
Const AWS_BUCKETNAME = "uk-bucketname"
Const AWS_ACCESSKEY = "GOES HERE"
Const AWS_SECRETKEY = "SECRET"
LocalFile = Server.Mappath("/test.jpg")
Dim sRemoteFilePath
sRemoteFilePath = "/files/test.jpg" 'Remote Path, note that AWS paths (in fact they aren't real paths) are strictly case sensitive
Dim strNow
strNow = GMTNow() ' GMT Date String
Dim StringToSign
StringToSign = Replace("PUT\n\nimage/jpeg\n\nx-amz-date:" & strNow & "\n/"& AWS_BUCKETNAME & sRemoteFilePath, "\n", vbLf)
Dim Signature
Signature = BytesToBase64(HMACSHA1(AWS_SECRETKEY, StringToSign))
Dim Authorization
Authorization = "AWS " & AWS_ACCESSKEY & ":" & Signature
Dim AWSBucketUrl
AWSBucketUrl = "https://" & AWS_BUCKETNAME & ".s3.amazonaws.com"
With Server.CreateObject("MSXML2.ServerXMLHTTP.6.0")
.open "PUT", AWSBucketUrl & sRemoteFilePath, False
.setRequestHeader "Authorization", Authorization
.setRequestHeader "Content-Type", "image/jpeg"
.setRequestHeader "Host", AWS_BUCKETNAME & ".s3.amazonaws.com"
.setRequestHeader "x-amz-date", strNow
.send GetBytes(LocalFile) 'Get bytes of local file and send
If .status = 200 Then ' successful
Response.Write "<a href="& AWSBucketUrl & sRemoteFilePath &" target=_blank>Uploaded File</a>"
Else ' an error ocurred, consider xml string of error details
Response.ContentType = "text/xml"
Response.Write .responseText
End If
End With
Function GetBytes(sPath)
With Server.CreateObject("Adodb.Stream")
.Type = 1 ' adTypeBinary
.Open
.LoadFromFile sPath
.Position = 0
GetBytes = .Read
.Close
End With
End Function
Function BytesToBase64(varBytes)
With Server.CreateObject("MSXML2.DomDocument").CreateElement("b64")
.dataType = "bin.base64"
.nodeTypedValue = varBytes
BytesToBase64 = .Text
End With
End Function
Function HMACSHA1(varKey, varValue)
With Server.CreateObject("System.Security.Cryptography.HMACSHA1")
.Key = UTF8Bytes(varKey)
HMACSHA1 = .ComputeHash_2(UTF8Bytes(varValue))
End With
End Function
Function UTF8Bytes(varStr)
With Server.CreateObject("System.Text.UTF8Encoding")
UTF8Bytes = .GetBytes_4(varStr)
End With
End Function
%>
The Amazon Signature must be url encoded in a slightly different way to what VBSCript encodes. The following function will encode the result correctly:
JScript Version:
function amazonEncode(s)
{
return Server.UrlEncode(s).replace(/\+/g,"%20").replace(/\%2E/g,".").replace(/\%2D/g,"-").replace(/\%7E/g,"~").replace(/\%5F/g,"_");
}
VBScript Version:
function amazonEncode(s)
dim retval
retval = Server.UrlEncode(s)
retval = replace(retval,"+","%20")
retval = replace(retval,"%2E",".")
retval = replace(retval,"%2D","-")
retval = replace(retval,"%7E","~")
retval = replace(retval,"%5F","_")
amazonEncode = retval
end function
As for base64, I used .NET's already built functionality for it. I had to create a DLL to wrap it, so that I could use it from JScript (or VBScript).
Here's how to create that dll:
Download the free C# 2010 Express and install it.
You also need to use two other tools that you won’t have a path to, so you will need to add the path to your PATH environment variable, so at a cmd prompt search for regasm.exe, guidgen.exe and sn.exe (you might find several versions – select the one with the latest date).
• cd\
• dir/s regasm.exe
• dir/s sn.exe
• dir/s guidgen.exe
So as an example, a COM object that has just one method which just returns “Hello”:
Our eventual aim is to use it like this:
<%#Language=JScript%>
<%
var x = Server.CreateObject("blah.whatever");
Response.Write(x.someMethod());
%>
or
<%#Language=VBScript%>
<%
dim x
set x = Server.CreateObject("blah.whatever")
Response.Write x.someMethod()
%>
• Start C# and create a new project
• Select “Empty Project”
• Give it a name – this becomes the namespace by default (the blah in the sample above)
• Next save the project (so you know where to go for the next bit). This will create a folder structure like so:
o blah this contains your solution files that the editor needs (blah.sln etc)
 blah this contains your source code and project files
• bin
o Debug the compiled output ends up here
• Next, using the cmd console, navigate to the root blah folder and create a key pair file:
sn –k key.snk
• Next you need a unique guid (enter guidgen at the cmd prompt)
o Select registry format
o Click “New Guid”
o Click “Copy”
• Back to C# editor – from the menu, select Project – Add Class
• Give it a name – this is the whatever in the sample above
• After the opening brace just after the namespace line type:
[GuidAttribute(“paste your guid here”)]
remove the curly brackets from your pasted guid
• You will need to add another “using” at the top
using System.Runtime.InteropServices;
• Finally you need to create someMethod
The final C# code looks like this (the bits in red may be different in your version):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace blah
{
[GuidAttribute("AEF4F27F-9E97-4189-9AD5-64386A1699A7")]
public class whatever
{
public string someMethod()
{
return "Hello";
}
}
}
• Next, from the menu, select Project – Properties
o On the left, select Application and, for the Output type dropdown, select “Class Library”
o On the left, select Signing and tick the “Sign the assembly” box, then browse to the key.snk file you made earlier
o Save the properties (CTRL-S)
• Next build the dll (Press F6) – This will create a dll in the Debug folder
• Open a cmd window as administrator (right click cmd.exe and select “Run as Administrator”)
• Navigate to the Debug folder and enter the following to register the assembly:
regasm blah.dll /tlb:blah.tlb /codebase blah
That’s it – the above is a genuine COM component and will work in other applications, the example below allows for event handling and only really works in ASP due to the default property mechanism of ASP:
The code for the base64 stuff would be:
// returns a base 64 encoded string that has been encrypted with SHA256
// parameters:
// s string to encrypt
// k key to use during encryption
public string getBase64SHA256(string s, string k)
{
HMACSHA256 sha = new HMACSHA256();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
sha.Key = encoding.GetBytes(k);
byte[] hashBytes = sha.ComputeHash(encoding.GetBytes(s));
return System.Convert.ToBase64String(hashBytes);
}
// returns a base 64 encoded string that has been encrypted with SHA1
// parameters:
// s string to encrypt
// k key to use during encryption
public string getBase64SHA1(string s, string k)
{
HMACSHA1 sha = new HMACSHA1();
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
sha.Key = encoding.GetBytes(k);
byte[] hashBytes = sha.ComputeHash(encoding.GetBytes(s));
return System.Convert.ToBase64String(hashBytes);
}
You would need the relevant usings:
using System.Security.Cryptography;
The signature in full must have all the query string name-value pairs in alphabetical order before computing the SHA and base64. Here is my version of the signature creator function:
function buildAmazonSignature(host,req,qstring)
{
var str="", i, arr = String(qstring).split("&");
for (i=0; i<arr.length; i++)
arr[i] = arr[i].split("=");
arr.sort(amazonSortFunc);
for (i=0; i<arr.length; i++)
{
if (str != "")
str += "&";
str += arr[i][0] + "=" + arr[i][1];
}
str = "GET\n"+host+"\n"+req+"\n"+str;
var utils = Server.CreateObject("FMAG.Utils");
var b64 = utils.getBase64SHA256(str, "xxxxxxxxxx");
utils = null;
return amazonEncode(b64);
}
function amazonSortFunc(a,b)
{
return (a[0]<b[0])?-1:((a[0]>b[0])?1:0);
}
VBScript doesn't have a very good array sort facility, so you'll have to work that one out yourself - sorry
Also I have the timestamp in this format:
YYYY-MM-DDTHH:MM:SSZ
Also the stuff in the query string included the following:
AWSAccessKeyId
SignatureMethod
SignatureVersion
Version
Expires
Action
Hope that helps
Thank you so much for this question, it has been such a great help to start my WSH/VBScript for my S3 backup service ;-)
I do not have much time, so I will not go through the details of the things I have changed from Chris' code, but please find below my little prototype script which works perfectly ;-)
This is just a WSH/VBScript, so you do not need IIS to run it, you just need to paste the content in a file with the ".vbs" extension, and you can then directly execute it ;-)
Option Explicit
'-- Amazon Web Services > My Account > Access Credentials > Access Keys --'
Dim strAccessKeyID: strAccessKeyID = "..."
Dim strSecretAccessKey: strSecretAccessKey = "..."
'-- Parameters: --'
Dim strLocalFile: strLocalFile = "..."
Dim strRemoteFile: strRemoteFile = "..."
Dim strBucket: strBucket = "..."
'-- Authentication: --'
Dim strNowInGMT: strNowInGMT = NowInGMT()
Dim strStringToSign: strStringToSign = _
"PUT" & vbLf & _
"" & vbLf & _
"text/xml" & vbLf & _
strNowInGMT & vbLf & _
"/" & strBucket + "/" & strRemoteFile
Dim strSignature: strSignature = ConvertBytesToBase64(HMACSHA1(strSecretAccessKey, strStringToSign))
Dim strAuthorization: strAuthorization = "AWS " & strAccessKeyID & ":" & strSignature
'-- Upload: --'
Dim xhttp: Set xhttp = CreateObject("MSXML2.ServerXMLHTTP")
xhttp.open "PUT", "http://" & strBucket & ".s3.amazonaws.com/" & strRemoteFile, False
xhttp.setRequestHeader "Content-Type", "text/xml"
xhttp.setRequestHeader "Date", strNowInGMT 'Yes, this line is mandatory ;-) --'
xhttp.setRequestHeader "Authorization", strAuthorization
xhttp.send GetBytesFromFile(strLocalFile)
If xhttp.status = "200" Then
WScript.Echo "The file has been successfully uploaded ;-)"
Else
WScript.Echo "There was an error :-(" & vbCrLf & vbCrLf & _
xhttp.responseText
End If
Set xhttp = Nothing
'-- NowInGMT ------------------------------------------------------------------'
Function NowInGMT()
'This is probably not the best implementation, but it works ;-) --'
Dim sh: Set sh = WScript.CreateObject("WScript.Shell")
Dim iOffset: iOffset = sh.RegRead("HKLM\System\CurrentControlSet\Control\TimeZoneInformation\ActiveTimeBias")
Dim dtNowGMT: dtNowGMT = DateAdd("n", iOffset, Now())
Dim strDay: strDay = "NA"
Select Case Weekday(dtNowGMT)
Case 1 strDay = "Sun"
Case 2 strDay = "Mon"
Case 3 strDay = "Tue"
Case 4 strDay = "Wed"
Case 5 strDay = "Thu"
Case 6 strDay = "Fri"
Case 7 strDay = "Sat"
Case Else strDay = "Error"
End Select
Dim strMonth: strMonth = "NA"
Select Case Month(dtNowGMT)
Case 1 strMonth = "Jan"
Case 2 strMonth = "Feb"
Case 3 strMonth = "Mar"
Case 4 strMonth = "Apr"
Case 5 strMonth = "May"
Case 6 strMonth = "Jun"
Case 7 strMonth = "Jul"
Case 8 strMonth = "Aug"
Case 9 strMonth = "Sep"
Case 10 strMonth = "Oct"
Case 11 strMonth = "Nov"
Case 12 strMonth = "Dec"
Case Else strMonth = "Error"
End Select
Dim strHour: strHour = CStr(Hour(dtNowGMT))
If Len(strHour) = 1 Then strHour = "0" & strHour End If
Dim strMinute: strMinute = CStr(Minute(dtNowGMT))
If Len(strMinute) = 1 Then strMinute = "0" & strMinute End If
Dim strSecond: strSecond = CStr(Second(dtNowGMT))
If Len(strSecond) = 1 Then strSecond = "0" & strSecond End If
Dim strNowInGMT: strNowInGMT = _
strDay & _
", " & _
Day(dtNowGMT) & _
" " & _
strMonth & _
" " & _
Year(dtNowGMT) & _
" " & _
strHour & _
":" & _
strMinute & _
":" & _
strSecond & _
" +0000"
NowInGMT = strNowInGMT
End Function
'-- GetBytesFromString --------------------------------------------------------'
Function GetBytesFromString(strValue)
Dim stm: Set stm = CreateObject("ADODB.Stream")
stm.Open
stm.Type = 2
stm.Charset = "ascii"
stm.WriteText strValue
stm.Position = 0
stm.Type = 1
GetBytesFromString = stm.Read
Set stm = Nothing
End Function
'-- HMACSHA1 ------------------------------------------------------------------'
Function HMACSHA1(strKey, strValue)
Dim sha1: Set sha1 = CreateObject("System.Security.Cryptography.HMACSHA1")
sha1.key = GetBytesFromString(strKey)
HMACSHA1 = sha1.ComputeHash_2(GetBytesFromString(strValue))
Set sha1 = Nothing
End Function
'-- ConvertBytesToBase64 ------------------------------------------------------'
Function ConvertBytesToBase64(byteValue)
Dim dom: Set dom = CreateObject("MSXML2.DomDocument")
Dim elm: Set elm = dom.CreateElement("b64")
elm.dataType = "bin.base64"
elm.nodeTypedValue = byteValue
ConvertBytesToBase64 = elm.Text
Set elm = Nothing
Set dom = Nothing
End Function
'-- GetBytesFromFile ----------------------------------------------------------'
Function GetBytesFromFile(strFileName)
Dim stm: Set stm = CreateObject("ADODB.Stream")
stm.Type = 1 'adTypeBinary --'
stm.Open
stm.LoadFromFile strFileName
stm.Position = 0
GetBytesFromFile = stm.Read
stm.Close
Set stm = Nothing
End Function
Dear stone-edge-technology-VBScript-mates (*), let me know if it is working for you as well ;-)
(*) This is a reference to the comment from Spudley, see above ;-)