Sei sulla pagina 1di 7

http://www.dreamincode.

net/forums/topic/33331-upload-using-http/
Re: Upload using HTTP
Posted 30 August 2010 - 06:53 AM
Hi nomlah25,

this my code vb6 for upload many files:

in Project:
Add References "Microsoft WinHTTP Services, version 5.1" : winhttp.dll

in Form:
Add Text1.text="", Text2.text="value1=1&value2=2"
Add buttons: Command1.Caption="Upload File", b_leerURL.Caption="LeerURL",
b_downloadurl.Caption="Download File"
in code form :
Private Sub b_downloadurl_Click()
Text1.Text = downloadFile("http://10.6.105.34/upload06/getfile.php", App.Path +
"\bajando_getfile.php")
End Sub

Private Sub b_leerurl_Click()


Text1.Text = Replace(LeerURL("http://10.6.105.34/upload05/"), vbLf, vbNewLine, , ,
vbBinaryCompare) 'LeerURL("http://localhost/upload05/")
End Sub

Private Sub Command1_Click()

ReDim LIS_AR(3)
LIS_AR(1).ruta_ar = "c:\reporte_getPacienteByFechaModificacion_20100908.pdf"
LIS_AR(1).nombre_ar = "archivo1.pdf"
LIS_AR(2).ruta_ar = "c:\XqueryProperties.xml"
LIS_AR(2).nombre_ar = "archivo1.xml"
LIS_AR(3).ruta_ar = "c:\ReporteAction[1].htm"
LIS_AR(3).nombre_ar = "archivo1.htm"

'Set path to php upload script here


Text1.Text = Replace(uploadFiles("http://10.6.105.34/upload06/getfile.php",
App.Path, Text2.Text), vbLf, vbNewLine, , , vbBinaryCompare)

End Sub
---
incode module:
'/// INI DOWNLOAD FILE
Option Explicit
Private Declare Function URLDownloadToFile Lib "urlmon" Alias "URLDownloadToFileA"
(ByVal pCaller As Long, ByVal szURL As String, ByVal szFileName As String, ByVal
dwReserved As Long, ByVal lpfnCB As Long) As Long
Private Declare Function InternetOpen Lib "wininet" Alias "InternetOpenA" (ByVal
sAgent As String, ByVal lAccessType As Long, ByVal sProxyName As String, ByVal
sProxyBypass As String, ByVal lFlags As Long) As Long
Private Declare Function InternetCloseHandle Lib "wininet" (ByVal hInet As Long) As
Integer
'/// FIN DOWNLOAD FILE

'/// INI READ URL


'Option Explicit
'Public Declare Function InternetOpen Lib "wininet.dll" Alias "InternetOpenA"
(ByVal sAgent As String, ByVal lAccessType As Long, ByVal sProxyName As String,
ByVal sProxyBypass As String, ByVal lFlags As Long) As Long
Public Declare Function InternetOpenUrl Lib "wininet.dll" Alias "InternetOpenUrlA"
(ByVal hInternetSession As Long, ByVal sURL As String, ByVal sHeaders As String,
ByVal lHeadersLength As Long, ByVal lFlags As Long, ByVal lContext As Long) As Long
Public Declare Function InternetReadFile Lib "wininet.dll" (ByVal hFile As Long,
ByVal sBuffer As String, ByVal lNumBytesToRead As Long, lNumberOfBytesRead As Long)
As Integer
'Public Declare Function InternetCloseHandle Lib "wininet.dll" (ByVal hInet As
Long) As Integer

Public Const IF_FROM_CACHE = &H1000000


Public Const IF_MAKE_PERSISTENT = &H2000000
Public Const IF_NO_CACHE_WRITE = &H4000000

Public Const BUFFER_LEN = 256


'/// FIN READ URL

'/// INI UPLOAD


'You need reference to Microsoft WinHTTP Services 5.0 or 5.1 to use this example
'http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=55649&lngWId=1
'Credit to Joseph Z. Xu (jzxu@napercom.com)
'Modified by Mohd Idzuan Alias (iklan2k@yahoo.com) August 18, 2004

Dim WinHttpReq As WinHttp.WinHttpRequest


Const HTTPREQUEST_SETCREDENTIALS_FOR_SERVER = 0
Const HTTPREQUEST_SETCREDENTIALS_FOR_PROXY = 1
Const BOUNDARY = "Xu02=$"
Const HEADER = "--Xu02=$"
Const FOOTER = "--Xu02=$--"

Public Type MULTIARCHI


ruta_ar As String
nombre_ar As String
End Type
Public LIS_AR() As MULTIARCHI
'/// FIN UPLOAD

'/// INI UPLOAD


Function uploadFiles(strURL As String, DirPath As String, Optional postVar As
String, _
Optional strUserName As String, Optional strPassword As
String) As String

Dim fname As String


Dim strFile As String
Dim strBody As String
Dim aPostBody() As Byte
Dim nFile As Integer
Dim i As Integer
Set WinHttpReq = New WinHttpRequest

' Turn error trapping on


On Error GoTo SaveErrHandler

' Assemble an HTTP request.


strURL = strURL & "?slots=" & CStr(UBound(LIS_AR)) & "&" & postVar
WinHttpReq.Open "POST", strURL, False
Debug.Print strURL
If strUserName <> "" And strPassword <> "" Then
' Set the user name and password.
WinHttpReq.SetCredentials strUserName, strPassword, _
HTTPREQUEST_SETCREDENTIALS_FOR_SERVER
End If

'-------------------------- Becareful not to mingle too much here


-----------------------------------

' Set the header


WinHttpReq.SetRequestHeader "Content-Type", "multipart/form-data; boundary=" &
BOUNDARY

' Assemble the body


strBody = HEADER ' Starting tag

For i = 1 To UBound(LIS_AR)

' Grap the file


strFile = getArchivoComoString(LIS_AR(i).ruta_ar)

strBody = strBody & vbCrLf & "Content-Disposition: form-data; name="""


& "upload" & _
i & """; filename=""" & LIS_AR(i).nombre_ar & """" & vbCrLf & "Content-
type: file" & _
vbCrLf & vbCrLf & strFile & vbCrLf

If i < UBound(LIS_AR) Then


strBody = strBody & "--Xu02=$" ' This is boundary tag between two files
End If
strFile = ""

Next i

strBody = strBody & FOOTER ' Ending tag

'----------------------------------------------------------------------------------
------------------

' Because of binary zeros, post body has to convert to byte array
aPostBody = StrConv(strBody, vbFromUnicode)

' Send the HTTP Request.


WinHttpReq.Send aPostBody

' Display the status code and response headers.


'UploadFiles = WinHttpReq.GetAllResponseHeaders & " " &
WinHttpReq.ResponseText
uploadFiles = WinHttpReq.ResponseText

Set WinHttpReq = Nothing

Exit Function

SaveErrHandler:
uploadFiles = Err.Description

Set WinHttpReq = Nothing


End Function

Function getArchivoComoString(strFileName As String) As String


Dim strFile As String
Dim nFile As Variant
' Grap the file
nFile = FreeFile
Open strFileName For Binary As #nFile
strFile = String(LOF(nFile), " ")
Get #nFile, , strFile
Close #nFile

getArchivoComoString = strFile

End Function

'/// FIN UPLOAD

'/// INI READ URL


Public Function LeerURL(sURL As String) As String
Dim sBuffer As String * BUFFER_LEN, iResult As Integer, sData As String
Dim hInternet As Long, hSession As Long, lReturn As Long

'get the handle of the current internet connection


hSession = InternetOpen("vb wininet", 1, vbNullString, vbNullString, 0)
'get the handle of the url
If hSession Then hInternet = InternetOpenUrl(hSession, sURL, vbNullString, 0,
IF_NO_CACHE_WRITE, 0)
'if we have the handle, then start reading the web page
If hInternet Then
'get the first chunk & buffer it.
iResult = InternetReadFile(hInternet, sBuffer, BUFFER_LEN, lReturn)
sData = sBuffer
'if there's more data then keep reading it into the buffer
Do While lReturn <> 0
iResult = InternetReadFile(hInternet, sBuffer, BUFFER_LEN, lReturn)
sData = sData + Mid(sBuffer, 1, lReturn)
Loop
End If

'close the URL


iResult = InternetCloseHandle(hInternet)

LeerURL = sData
End Function

Function downloadFile(sURLFileName As String, sSaveToFile As String, Optional


bOverwriteExisting As Boolean = False) As Boolean
Dim lRet As Long
Const S_OK As Long = 0, E_OUTOFMEMORY = &H8007000E
Const INTERNET_OPEN_TYPE_PRECONFIG = 0, INTERNET_FLAG_EXISTING_CONNECT =
&H20000000
Const INTERNET_OPEN_TYPE_DIRECT = 1, INTERNET_OPEN_TYPE_PROXY = 3
Const INTERNET_FLAG_RELOAD = &H80000000

On Error Resume Next


'Create an internet connection
lRet = InternetOpen("", INTERNET_OPEN_TYPE_DIRECT, vbNullString, vbNullString,
0)
If bOverwriteExisting Then
If Len(Dir$(sSaveToFile)) Then
VBA.Kill sSaveToFile
End If
End If
'Check file doesn't already exist
If Len(Dir$(sSaveToFile)) = 0 Then
'Download file
lRet = URLDownloadToFile(0&, sURLFileName, sSaveToFile, 0&, 0)
If Len(Dir$(sSaveToFile)) Then
'File successfully downloaded
downloadFile = True
Else
'Failed to download file
If lRet = E_OUTOFMEMORY Then
Debug.Print "El largo de buffer es inv�lido o tiene insuficiente
memoria para completar la operaci�n."
Else
Debug.Assert False
Debug.Print "Error ocurri� " & lRet & " (probablemente un error del
servidor proxy)."
End If
downloadFile = False
End If
End If
On Error GoTo 0

End Function

------
in getfile.php:
<?php

//Put this php upload script in your apache php webserver.


//Set the url to this script in your vb upload client

$location = "archivossubidos/"; //Left blank if upload in same folder


$max_size = 1000000; //File upload size

$value1=$_REQUEST['value1'];
$value2=$_REQUEST['value2'];
$slots=$_REQUEST['slots'];

echo "slots=".$slots.", value1=".$value1.", value2=".$value2."\r\n"; //Check for


extra posted variable - u can add ur own here

//This loop here will save ur file to the server


echo "total archivos:".count($_FILES)."\n";
for ($num = 1; $num < $slots+1; $num++){
$event = "ini:paso_num=".$num.", archivo=".$_FILES['upload'.$num]
['name']."\n";
//$event = "ini:paso_num=".$num.", archivo=".$_FILES['upload1']['name']."\n";
echo $event."\n";
// left: substr($value, 0, $count);
// right: substr($value, ($count*-1));

// Check if upload for field is required


if (! $_FILES['upload'.$num]['name'] == ""){
//if (! $_FILES['upload1']['name'] == ""){
$event = "paso1";
echo $event."\n";
if ($_FILES['upload'.$num]['size'] < $max_size) {
//if ($_FILES['upload1']['size'] < $max_size) {
$event = "paso2";
echo $event."\n";
//move_uploaded_file($_FILES['upload'.$num]['tmp_name'],
$location.$_FILES['upload'.$num]['name']) or $event = "Failure";
copy($_FILES['upload'.$num]['tmp_name'],$location.
$_FILES['upload'.$num]['name']) or $event = "Failure";
//copy($_FILES['upload1']['tmp_name'],$location.
$_FILES['upload1']['name']) or $event = "Failure";
$event = "paso3";
echo $event."\n";
}
else {
$event = "paso4";
echo $event."\n";
$event = "File too large!\n";
$event = "paso5";
echo $event."\n";
}
$event = "paso6";
echo $event."\n";
echo "Uploading File $num $event\r\n";
$event = "paso7";
echo $event."\n";
}
$event="paso8";
echo $event."\n";
}

echo "event_final=".$event."\n";
?>
----------
Here is enviaarchi.php (only show manual upload process)
<html>
<head>
<title>Enviar Archivo al Servidor Repositorio de Logs</title>
</head>
<body>
<form enctype="multipart/form-data" action="./getfile.php" method="post">
<p>Variable1: <input type="text" name="value1" /></p>
<p>Variable2: <input type="text" name="value2" /></p>

<p>Variable3: <input type="text" name="slots" value="1" /></p>


<p>File: <input type="file" name="upload1" /></p>
<p><input type="submit" value="Post" /></p>
</form>
</body>
</html>
----------

my files in web server:


destiny directory files:
c:\wamp\www\upload06\archivossubidos\
process file uploaded:
c:\wamp\www\upload06\getfile.php
manual process upload:
c:\wamp\www\upload06\enviaarchi.php

You should give all permissions in web site to try this code previously (chmod 775)

I hope solve your problem :D


Regards,
RodrigoH

Potrebbero piacerti anche