场景
已经获取了图片的地址,想直接通过这个链接上传到网站指定位置
操作步骤
- 找到上传图片对应的控件,一般都是
input,
在谷歌浏览器的Elements中 搜索input[type='file']
,一般就是需要的对象了 - 找到对应的对象,执行以下代码即可上传成功
let list = new DataTransfer(); let xhr = new XMLHttpRequest(); xhr.open("GET", "https://****"); xhr.responseType = "blob"; xhr.onload = function () { let file_name = image.split('/')[image.split('/').length - 1]; let f = new File([xhr.response], file_name, {type: "image/jpeg"}); list.items.add(f);} xhr.send(null); //let f = new File(['tesf file'], "text.txt", {type: "text/plain"}); //需上传的文件 //list.items.add(f); //let input = $('[type="file"]')[0] let input = document.querySelector('[type="file"]') input.files= list.files; let event_change = new Event('change',{ bubbles: true }); input.dispatchEvent(event_change); //执行change上传文件
以上代码中注释的代码let input = $('[type="file"]')[0]'
, 需要导入jquery,执行以下代码后,就可以正常执行
var jq = document.createElement('script');
jq.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(jq);