@[TOC](VBA 上传图片)
问题来源于帖子:VBA怎么样通过winHttp、xmlHttp post上传图片呢 求大佬指点
整个过程并没有什么加密,比较简单,就不做什么分析了,使用Fiddler抓包查看,可以很快的用python复现
import requests
from io import BytesIO
from requests_toolbelt.multipart.encoder import MultipartEncoder
def main():
file_name = '6da2ddc8124d0ba7045c38925eb857c0.jpeg'
fields = {
"image": (file_name, BytesIO(open(file_name, 'rb').read()), 'image/jpeg'),
"fileId": file_name,
"initialPreview": '[]',
"initialPreviewConfig": '[]',
"initialPreviewThumbTags": '[]'
}
multipart = MultipartEncoder(
fields=fields,
boundary='----WebKitFormBoundaryAx0QwuMECh2eIreV'
)
headers = {
"X-Requested-With": "XMLHttpRequest",
"Content-Type": multipart.content_type,
}
data = multipart.to_string()
response = requests.post('https://www.imgtp.com/upload/upload.html', headers=headers, data=data)
print(response.status_code)
print(response.headers)
print(response.request.headers)
print(response.json())
if __name__ == '__main__':
main()
基本上都是照抄,最后可以获取在线的图片地址。这么难点在于如何使用VBA来上传。
1.因为没有轮子,所有multipart 包装需要自己处理。
2.请求体包含了二进制文件
一、
为了解决第一个问题,可以在vba中生成的二进制数据(即Byte数组)与python的对比,直到两个数据完全一样。
二、因为要提交字节数组,那么必须要使用【WinHttp.WinHttpRequest.5.1】对象。
提交部分的代码如下
Sub upload()
Const Boundary As String = "----WebKitFormBoundaryAx0QwuMECh2eIreV"
Const file_name As String = "6da2ddc8124d0ba7045c38925eb857c0.jpeg"
Dim image_byte() As Byte
Dim data() As Byte
image_byte = openbytefile(ActiveWorkbook.path & "\" + file_name)
Dim bytes As bytearray
Set bytes = New bytearray
bytes.update encodeutf8("--" & Boundary & vbNewLine)
bytes.update encodeutf8("Content-Disposition: form-data; name=""image""; filename=""" & file_name & """" & vbNewLine)
bytes.update encodeutf8("Content-Type: image/jpeg" & vbNewLine)
bytes.update encodeutf8(vbNewLine)
bytes.update image_byte
支付6UD,阅读全文
还有更多的精彩内容,作者设置为付费后可见