I am looking to create a VBS script that can post three parameters as well as upload a file. I have a PHP file sitting on the server which is working perfectly using a form to send the parameters and file, but I want to create a script that means I don't require the form at all and could POST directly from a script.
I am really struggling to find any good / working examples... I wondered if anyone could point me in the right direction?
This is my PHP file
<?php
$parameter1 = $_GET['parameter1'];
$parameter2 = $_GET['parameter2'];
$parameter3 = $_GET['parameter3'];
$tempname = $dataname."--". date("Y_m_d--H_i_s--"). "file.txt";
$filename = '/myfiles/'. $tempname;
if (move_uploaded_file($_FILES['filechoice']['tmp_name'], $filename)) {
echo "uploaded succesfully";
} else {
echo "error uploading";
}
?>
This is the VBScript I have put together via a few sources so far....
Dim strURL
Dim HTTP
Dim dataFile
Dim dataRequest
Dim objStream
strURL = "http://localhost/uploadfile.php?parameter1=mytest1¶meter2=hello¶meter3=thankyou"
Set HTTP = CreateObject("Microsoft.XMLHTTP")
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = 2
objStream.Open
objStream.LoadFromFile "c:\1234.txt"
dataFile = objStream.ReadText
dataRequest = "filechoice=" & dataFile
HTTP.open "POST", strURL, False
HTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
HTTP.setRequestHeader "Content-Length", Len(dataRequest)
WScript.Echo "Now uploading file"
HTTP.send dataRequest
WScript.Echo HTTP.responseText
Set HTTP = Nothing
I have used print_r($_GET) on the PHP file and can see the parameters are being sent perfectly....
But if I try and look for a file i.e print_r($_FILES) - it shows nothing and nothing is uploaded..
Related
I'm unable to upload files using the Dio plugin and I can not figure out where's the problem. In Laravel the request is always empty.
What have I done so far:
Double check if the file path really exists using existsSync() function
Changed the Content-Type to application/x-www-form-urlencoded
Validated if the file is actually being uploaded - seems yes (?)
This is my flutter code:
File myFile = new File('/storage/emulated/0/Download/demo.docx');
FormData form = new FormData.from({
'title': 'Just testing',
'file': new UploadFileInfo(myFile, 'demo.docx')
});
Before sending through POST i checked if the file exists and returns true
print(myFile.existsSync());
And set the Content-type properly
Response response = await Dio().post(
myUrl,
data: form,
options: new Options(
contentType: ContentType.parse("application/x-www-form-urlencoded"),
),
);
Printing the result of the form returns
I/flutter (27929): ----dio-boundary-0118165894
I/flutter (27929): Content-Disposition: form-data; name="title"
I/flutter (27929): ----dio-boundary-1759467036
I/flutter (27929): Content-Disposition: form-data; name="file"; filename="demo.docx"
I/flutter (27929): Content-Type: application/octet-stream
Which I believe indicates that the file is being uploaded.
Now in laravel whenever i output the content received it always comes null the key file, but the key title comes with data.
The code print_r(json_encode($request->all())) retrieves
{"title":"Just testing","file":{}}
The same goes for print_r(json_encode($request->file('file'))).
What am i missing?
Solved.
This took me a while to figure it out, but i end up realizing there's two problems with this approach:
Laravel $request is empty, but $_FILES is not
Sending multiple files can not be sent using arrays as the documentation tells
So, in order to achieve my goal which allows the user to select multiple files dynamically and upload them at the same time, here's the logic behind:
Flutter
The form must be created without setting the files right away:
FormData form = new FormData.from(
{
'title': 'Just testing',
});
Since the function .from is a Map<String, dynamic> values can be added after.
/*
* files = List<String> containing all the file paths
*
* It will end up like this:
* file_1 => $_FILES
* file_2 => $_FILES
* file_3 => $_FILES
*/
for (int i = 0; i < files.length; i++) {
form.add('file_' + i.toString(),
new UploadFileInfo(new File(files[i]), files[i].toString()));
}
There is no need to set up a different Content-Type, therefore this is enough:
Response response = await Dio().post(myUrl, data: form);
Laravel / PHP
Forget about accessing the file through $request->file() and instead use the old school approach.
$totalFiles = count($_FILES);
for ($i = 0; $i < $totalFiles; $i++)
{
$file = $_FILES['file_' . $i];
// handle the file normally ...
$fileName = basename($file['name']);
$fileInfo = pathinfo($file);
$fileExtension = $fileInfo['extension'];
move_uploaded_file($file['tmp_name'], $path);
}
I know this is an old post but this may help someone.
this solution works for me, upload multi-file to server use Flutter Dio library and Laravel as backend. correct me if I did it wrong.
Flutter
BaseOptions _dioOption({#required String token}) {
BaseOptions options = new BaseOptions(baseUrl: baseUrl, headers: {
Headers.acceptHeader: Headers.jsonContentType,
Headers.contentTypeHeader: Headers.jsonContentType,
"Authorization": "Bearer $token"
});
return options;
}
dioPostProduct( {#required ProductToUpload productToUpload,
#required String url, String token}) async {
//productToUpload.images is a List<File>
List<Object> filesData = new List<Object>();
for (final file in productToUpload.images) {
filesData.add(MultipartFile.fromFileSync(file.path,
filename: file.path.split('/').last));
}
FormData data = FormData.fromMap({
"subcategory_id": productToUpload.subcategory_id,
"name": productToUpload.name,
"detail": productToUpload.detail,
"price": productToUpload.price,
"condition_id": productToUpload.condition_id,
"images": filesData,
});
Dio dio = new Dio(_dioOption(token: token));
Response response;
response = await dio.post(url, data: data);
if (response.statusCode == 200) {
print(response.data);
}
}
Laravel
For php resize image I use library intervention
$images = Collection::wrap(request()->file('images'));
$directory = '/product_images'; //make sure directory is exist
foreach ($images as $image) {
$basename = Str::random();
$original = $basename . '.' . $image->getClientOriginalExtension();
$thumbnail = $basename . '_thumb.' . $image->getClientOriginalExtension();
Image::make($image)
->fit(400, 400)
->save(public_path($directory . '/' . $thumbnail));
$image->move(public_path($directory), $original);
}
My application (written in vb.net) send data to a php script hosted on one of the free webhosting servers. The php script evaluates the data, and responds accordingly. The response from the server looks something like this:
Valid
<!-- Hosting3322 Analytics Code -->
<script type="text/javascript" src="theurlforthewebsite/count.php"></script>
<!-- End of Analytics Code -->
'Valid' is from my php script. Rest of is a little script by the server that they hide in every page.
Here is the php script:
<?php
$d = $_POST['mac'];
if($d=='45bgd0434')
echo "Valid";
else
echo "Invalid";
?>
Here is my vb.net code:
' Create a request using a URL that can receive a post.
Dim request As WebRequest = WebRequest.Create("http://sitename.com/verify.php")
' Set the Method property of the request to POST.
request.Method = "POST"
' Create POST data and convert it to a byte array.
Dim postData As String = "mac=45bgd0434"
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)
' Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded"
' Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length
' Get the request stream.
Dim dataStream As Stream = request.GetRequestStream()
' Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length)
' Close the Stream object.
dataStream.Close()
' Get the response.
Dim response As WebResponse = request.GetResponse()
' Get the stream containing content returned by the server.
dataStream = response.GetResponseStream()
' Open the stream using a StreamReader for easy access.
Dim reader As New StreamReader(dataStream)
' Read the content.
Dim responseFromServer As String = reader.ReadToEnd()
' Clean up the streams.
reader.Close()
dataStream.Close()
response.Close()
MessageBox.Show(responseFromServer)
I would just like to have only the output and not that extra code. Is there any way I can use an alternative method to print in PHP, or probably another method with which I can talk to the server?
I have tried other free servers on the internet, but they all seem to put in some code. Would really appreciate your help.
I am trying to make a script to upload any file to a simple html/php upload form.
I cannot find any working scripts that don't use ASP.
This is the closest code I have: (VBS)
Dim strURL
Dim HTTP
Dim dataFile
Dim dataRequest
Dim objStream
strURL = "http://10.0.0.50/~/v_upload/up.php"
Set HTTP = CreateObject("Microsoft.XMLHTTP")
Set objStream = CreateObject("ADODB.Stream")
Set dataFile = objStream.Read
objStream.Type = 2
objStream.Open
objStream.LoadFromFile "http.txt"
Set dataRequest = "dataFile=" & dataFile
HTTP.open "POST", strURL, False
HTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
HTTP.setRequestHeader "Content-Length", Len(dataRequest)
WScript.Echo "Now uploading file G:\Http\http.txt"
HTTP.send dataRequest
WScript.Echo HTTP.responseText
Set HTTP = Nothing
This give me this error:
Line 9
Char 1
Error: Operation is not allowed when the object
is closed
Code 800A0E78
Source ADODB.Stream
The PHP code is:
<?php
if (!isset($_FILES['dataFile']['error']) || is_array($_FILES['dataFile']['error'])) {
switch ($_FILES['dataFile']['error']) {
case UPLOAD_ERR_OK:
break;
case UPLOAD_ERR_NO_FILE:
echo 'Unable to Upload. No file sent.';
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
echo 'Unable to Upload. Exceeded file size limit.';
default:
echo 'Unable to Upload. Unknown errors.';
}
die();
}
$file_path = "http/";
$file_path = $file_path . basename( $_FILES['dataFile']['name']);
if(move_uploaded_file($_FILES['dataFile']['tmp_name'], $file_path)) {
echo "File {$_FILE['dataFile']['name']} uploaded success";
} else{
echo "Unable to upload. Unable to move uploaded file.";
}
?>
Please Help!
There are basically 4 errors that need to be repaired:
Remove set from line 9
Change objStream.Read to objStream.ReadText
Move line 9 to after objStream.LoadFromFile
Remove set from line 14
The Full Code:
Dim strURL
Dim HTTP
Dim dataFile
Dim dataRequest
Dim objStream
strURL = "http://10.0.0.50/~/v_upload/up.php"
Set HTTP = CreateObject("Microsoft.XMLHTTP")
Set objStream = CreateObject("ADODB.Stream")
objStream.Type = 2
objStream.Open
objStream.LoadFromFile "http.txt"
dataFile = objStream.ReadText
dataRequest = "dataFile=" & dataFile
HTTP.open "POST", strURL, False
HTTP.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
HTTP.setRequestHeader "Content-Length", Len(dataRequest)
WScript.Echo "Now uploading file G:\Http\http.txt"
HTTP.send dataRequest
WScript.Echo HTTP.responseText
Set HTTP = Nothing
This did not work for me, but I found this:
https://github.com/ArancioGrigio/vbs-php-ImageUpload
It transfers image to a php server by converting them to base64 and sending the text to server in packets of 2000 character through php GET parameters. At the end the php server converts text back to image.
I used vbs for client and php for server.
This is good for low traffic and low weight images, otherwise it could take some minutes and server could not respond anymore.
GET parameters limit is 2048 characters
I am trying to send a document file from Lotus Script to a web server and save it there. Unfortunately the file transfer does not work. I have a Lotusscript agent to get the document and this part is working ( str_filecontent contains the correct xml file ), but the file transfer or saving is not working. Here is my Lotusscript agent:
Option Public
Option Declare
Sub Initialize
'Declare long
Dim lng_resolveTimeout, lng_connectTimeout, lng_sendTimeout, lng_receiveTimeout As Long
'Declare integer
Dim int_serverCredentials As Integer
'Declare variants
Dim var_submitObject As Variant
'Set values
int_serverCredentials = 0
lng_resolveTimeout = 120000 'miliseconds = 2 minutes
lng_connectTimeout = 1200000
lng_sendTimeout = 1200000
lng_receiveTimeout = 1200000
'Create HTTP object
Set var_submitObject = CreateObject("WinHTTP.WinHTTPRequest.5.1")
Call var_submitObject.SetTimeouts(lng_resolveTimeout, lng_connectTimeout, lng_sendTimeout, lng_receiveTimeout)
'Standards for this post
%REM
Content-Type: multipart/form-data; boundary={boundary}
{boundary}
Content-Disposition: form-data; name="data"; filename="{filename}"
Content-Type: text/plain
{contents}
{boundary}--
%END REM
Dim str_url As String
str_url = "http://.../upload.php"
Dim str_AUTH As String
Dim str_boundary As String
Dim str_filecontent As String
str_filecontent = get_data()
Dim submitHTTP
'Set post parameters
Call var_submitObject.open("POST", str_url, False)
Call var_submitObject.setRequestHeader("Accept", "application/xml")
Call var_submitObject.setRequestHeader("Authorization", "Basic " & str_auth)
Call var_submitObject.setRequestHeader("Content-Type", "multipart/form-data; boundary=b1")
str_boundary = |--b1| & Chr(13) & Chr(10) &_
|Content-Disposition: form-data; name="data"; filename="name.txt"| & Chr(13) & Chr(10) &_
|Content-Type: text/plain| & Chr(13) & Chr(10) &_
str_fileContent & |b1--|
'Send the HTTP request
Call var_submitObject.Send(str_boundary)
'Wait for the answer and set object as returned value for further validation
Call var_submitObject.WaitForResponse
Set submitHTTP = var_submitObject
'Clear memory
Set var_submitObject = Nothing
End Sub
%REM
Function get_data
Description: Comments for Function
%END REM
Function get_data() As String
Dim session As New NotesSession
Dim doc As NotesDocument
' Dim db As NotesDatabase
Dim exporter As NotesDXLExporter
' Set db = session.CurrentDatabase
Dim workspace As New NotesUIWorkspace
Dim uidoc As NotesUIDocument
Set uidoc = workspace.CurrentDocument
Set doc = uidoc.Document
' Set doc = SESSION.CU
Set exporter = session.CreateDXLExporter
get_data = exporter.Export(doc)
Print get_data
End Function
Here is my web server PHP to receive and save the file:
<?php
define("UPLOAD_DIR", "/temp/");
if (!empty($_FILES["data"])) {
$myFile = $_FILES["data"];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>An error occurred.</p>";
exit;
}
// preserve file from temporary directory
$success = move_uploaded_file($myFile["tmp_name"],
UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
}
?>
Thanks for your time!
I'm trying to upload an image file to a PHP file on a web server.
On VB.NET ->
My.Computer.Network.UploadFile(tempImageLocation, "website.com/upload.php")
tempImageLocation is a location on the harddrive where the image is located. The image is located on the harddrive where I specify it.
On PHP ->
$image = $_FILES['uploads']['name'];
I don't understand, because it is loading the page - but PHP can't find the file under 'uploads'
Google brought me here while I was searching for the same question. Thanks people it gave me the idea, and with a little knowledge of PHP, I've achieved it. I know its an old question but still I'm going to share my code so it could help people in future..
VB:
My.Computer.Network.UploadFile("e:\file1.jpg", "http://www.mysite.com/upl/upl.php")
PHP:
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
and don't forget to give the upload folder the appropriate permissions.
I know, is old.. but here is solution work to me:
Private Sub HttpUploadFile(
ByVal uri As String,
ByVal filePath As String,
ByVal fileParameterName As String,
ByVal contentType As String)
Dim myFile As New FileInfo(filePath)
Dim sizeInBytes As Long = myFile.Length
Dim boundary As String = "---------------------------" & DateTime.Now.Ticks.ToString("x")
Dim newLine As String = System.Environment.NewLine
Dim boundaryBytes As Byte() = Encoding.ASCII.GetBytes(newLine & "--" & boundary & newLine)
Dim request As Net.HttpWebRequest = Net.WebRequest.Create(uri)
request.ContentType = "multipart/form-data; boundary=" & boundary
request.Method = "POST"
request.KeepAlive = True
'request.Credentials = Net.CredentialCache.DefaultCredentials
Using requestStream As IO.Stream = request.GetRequestStream()
Dim formDataTemplate As String = "Content-Disposition: form-data; name=""{0}""{1}{1}{2}"
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length)
Dim headerTemplate As String = "Content-Disposition: form-data; name=""{0}""; filename=""{1}""{2}Content-Type: {3};"
Dim header As String = String.Format(headerTemplate, fileParameterName, filePath, newLine, contentType)
header = header & vbNewLine & "Content-Length: " & sizeInBytes.ToString & vbNewLine
header = header & "Expect: 100-continue" & vbNewLine & vbNewLine
'MsgBox(header)
Debug.Print(header)
Dim headerBytes As Byte() = Encoding.UTF8.GetBytes(header)
requestStream.Write(headerBytes, 0, header.Length)
Using fileStream As New IO.FileStream(filePath, IO.FileMode.Open, IO.FileAccess.Read)
Dim buffer(4096) As Byte
Dim bytesRead As Int32 = fileStream.Read(buffer, 0, buffer.Length)
Do While (bytesRead > 0)
requestStream.Write(buffer, 0, bytesRead)
bytesRead = fileStream.Read(buffer, 0, buffer.Length)
Loop
End Using
Dim trailer As Byte() = Encoding.ASCII.GetBytes(newLine & "--" + boundary + "--" & newLine)
requestStream.Write(trailer, 0, trailer.Length)
requestStream.Close()
End Using
Dim response As Net.WebResponse = Nothing
Try
response = request.GetResponse()
Using responseStream As IO.Stream = response.GetResponseStream()
Using responseReader As New IO.StreamReader(responseStream)
Dim responseText = responseReader.ReadToEnd()
Debug.Print(responseText)
End Using
End Using
Catch exception As Net.WebException
response = exception.Response
If (response IsNot Nothing) Then
Using reader As New IO.StreamReader(response.GetResponseStream())
Dim responseText = reader.ReadToEnd()
Diagnostics.Debug.Write(responseText)
End Using
response.Close()
End If
Finally
request = Nothing
End Try
End Sub
Using:
HttpUploadFile("https://www.yousite.com/ws/upload.php?option1=sss&options2=12121", FULL_FILE_NAME_PATH_IN_YOUR_PC, "files", "multipart/form-data")
I copy somen code in a website i dont remember.
I only put this 2 lines of code to work:
header = header & vbNewLine & "Content-Length: " & sizeInBytes.ToString & vbNewLine
header = header & vbNewLine & "Expect: 100-continue" & vbNewLine
hope help.
Here is the complete example for uploading file using Visual Basic and on Server Side PHP (Rest API) GitHub Link
Here is quick and dirty tutorial for you: PHP File Upload
'uploads' is just name attribute value of element of a form:
<input type="file" name="uploads" />
or in other words, this is POST variable name that is accessed over $_FILES global.
If you don't set the field name, you can save the uploaded file with this
$file = array_shift($_FILES);
move_uploaded_file($file['tmp_name'], '/path/to/new/location/'.$file['name']);
Take a look at some of these other answers. PHP requires files uploaded with the POST method to use certain headers which are normally set by the browser when uploading from a web form but which can be set in VB with the HttpWebRequest Class.
As for the PHP side, you aren't going to be able to locate the file immediately after uploading with $image = $_FILES['uploads']['name'];. PHP stores uploads with a temporary filename accessible with the $_FILES['uploads']['tmp_name'] variable, and using move_uploaded_file() is the standard way of shifting uploads from temporary storage into a permanent uploads directory. The PHP manual provides a good overview of that.
Here's my sample server php file:
<?php
// write to a log file so you know it's working
$msg = $_POST['w'];
$logfile= 'data.txt';
$fp = fopen($logfile, "a");
fwrite($fp, $msg);
fclose($fp);
$file = array_shift($_FILES);
move_uploaded_file($file['tmp_name'], '/MAMP/htdocs/test/'.$file['name']);
?>
Here's the code to call #Rodrigo's code:
HttpUploadFile("http://localhost/test/test.php?w=hello&options2=12121", "C:\temp\bahamas.mp3", "files", "multipart/form-data")