我仍然是VBA的初学者,所以如果您需要进一步解释或我没有正确描述我的问题,请告诉我。
我正在尝试实现以下: 将文件从我的计算机上传到网站(如果您登录,则只能尝试上传,很遗憾,我无法共享链接)
为了达到这个目的,我需要做三件事: 1)点击"上传"按键 2)将Filepath插入PopUp Window的搜索字段 3)点击"打开"按钮
上传字段的HTML代码如下:
<div class="button-wrapper">
<input class="design-file-input" type="file">
<a class=" button prio1" href="javascript:void(0);">Design hochladen</a>
</div>
我想可能有两个解决方案,但是,我无法实现我的计划。
IDEA 1
以某种方式将文件路径放入输入字段和下载页面 因此我按照VBA代码尝试了vba:
objIE.document.getElementsByClassName("design-file-input")(0).Value
objIE.document.getElementsByClassName("design-file-input")(0).innerText
然后尝试以某种方式让网站提交我的参赛作品。
IDEA 2
点击&#34;设计Hochladen&#34;按钮。
objIE.document.getElementsByClassName("button-wrapper")(0).Click
然后PopUp窗口出现了,我不知道如何用VBA控制它
我很高兴听到并尝试你的建议!!如果您需要任何进一步的细节,请告诉我!非常感谢你,如果你能给我任何建议
答案 0 :(得分:1)
直接将文件路径分配给该特定HTML元素的值不起作用。不久前,我遇到了同样的问题(自动将文件传递到上传文件对话框)。经过长时间的谷歌搜索后,我找到了以下解决方案。不幸的是,我找不到此答案的链接。如果我访问该网站,我将与您分享链接:
Dim FilePath As String
Dim FileName As String
FilePath = Environ$("temp") & "\"
FileName = "test_file_for_upload" & ".xlsx"
UploadFile DestURL, FilePath & FileName, "file" 'Usage
'******************* upload - begin
'Upload file using input type=file
Public Sub UploadFile(DestURL As String, FileName As String, _
Optional ByVal FieldName As String = "File")
Dim sFormData As String, d As String
'Boundary of fields.
'Be sure this string is Not In the source file
Const Boundary As String = "---------------------------0123456789012"
'Get source file As a string.
sFormData = GetFile(FileName)
'Build source form with file contents
d = "--" + Boundary + vbCrLf
d = d + "Content-Disposition: form-data; name=""" + FieldName + """;"
d = d + " filename=""" + FileName + """" + vbCrLf
d = d + "Content-Type: application/upload" + vbCrLf + vbCrLf
d = d + sFormData
d = d + vbCrLf + "--" + Boundary + "--" + vbCrLf
'Post the data To the destination URL
IEPostStringRequest DestURL, d, Boundary
End Sub
'sends URL encoded form data To the URL using IE
Sub IEPostStringRequest(URL As String, FormData As String, Boundary As String)
'Create InternetExplorer
Dim WebBrowser: Set WebBrowser = CreateObject("InternetExplorer.Application")
'You can uncoment Next line To see form results
WebBrowser.Visible = True
'Send the form data To URL As POST request
Dim bFormData() As Byte
ReDim bFormData(Len(FormData) - 1)
bFormData = StrConv(FormData, vbFromUnicode)
WebBrowser.navigate URL, , , bFormData, _
"Content-Type: multipart/form-data; boundary=" + Boundary + vbCrLf
Do While WebBrowser.Busy
' Sleep 100
DoEvents
Loop
'WebBrowser.Quit
End Sub
'read binary file As a string value
Function GetFile(FileName As String) As String
Dim FileContents() As Byte, FileNumber As Integer
ReDim FileContents(FileLen(FileName) - 1)
FileNumber = FreeFile
Open FileName For Binary As FileNumber
Get FileNumber, , FileContents
Close FileNumber
GetFile = StrConv(FileContents, vbUnicode)
End Function
'******************* upload - end
第三个参数"file"
表示需要触发的HTML元素的ID。
希望这个解决方案对您也有用