我还是 VBA 的初学者,所以如果您需要进一步的解释或者我没有正确描述我的问题,请告诉我。
我正在努力实现以下目标: 将文件从我的计算机上传到网站(只有登录后才能尝试上传,遗憾的是我无法共享链接)
为了实现这一目标,我需要做三件事: 1)点击“上传”按钮 2) 将文件路径插入弹出窗口的搜索字段 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>
我想我的问题可能有两种解决方案,但是,我无法实现我的计划。
想法1
以某种方式将文件路径放入输入字段和下载它的页面 因此我尝试了以下VBA代码的vba:
objIE.document.getElementsByClassName("design-file-input")(0).Value
objIE.document.getElementsByClassName("design-file-input")(0).innerText
然后尝试以某种方式让网站提交我的条目。
想法2
单击“设计 Hochladen”按钮。
objIE.document.getElementsByClassName("button-wrapper")(0).Click
但是弹出窗口出现了,我不知道如何用VBA控制它
我很高兴听到并尝试您的建议!如果您需要任何进一步的详细信息,请告诉我!如果您能给我任何建议,非常感谢
最佳答案
直接将文件路径分配给该特定 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。
希望这个解决方案也适合您
关于vba - 上传文件到网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49059375/