发现一个微博图床API和图片上传代码

网上寻到一款微博图床的插件,然后顺藤摸瓜找到了原作者的API代码。

API文件:

 <?php
/**
* 上传图片到微博图床
* @author Youngxj & mengkun & 阿珏
* @param $file 图片文件/图片url
* @param $multipart 是否采用multipart方式上传
* @return 返回的json数据
* @code 200:正常;201:错误;203:cookie获取失败;404:请勿直接访问
* @ps 图片尺寸可供选择:square、thumb150、orj360、orj480、mw690、mw1024、mw2048、small、bmiddle、large 默认为:thumb150,请自行替换
*/
header("Access-Control-Allow-Origin:*");
header('Content-type: application/json');
error_reporting(0);
if (!is_file('sina_config.php')) {
CookieSet('SUB;','0');
}
include 'sina_config.php';
//账号
$sinauser = 'admin';
//密码
$sinapwd = 'password';
if (time() - $config['time'] >20*3600||$config['cookie']=='SUB;') {
$cookie = login($sinauser,$sinapwd);
if($cookie&&$cookie!='SUB;'){
CookieSet($cookie,$time = time());
}else{
return error('203','获取cookie出现错误,请检查账号状态或者重新获取cookie');
}
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {exit;}
$type=$_GET['type'];
if($type=='multipart'){
$multipart = true;
$file = $_FILES["file"]["tmp_name"];
}elseif(isset($_GET['img'])){
$multipart = false;
$file = $_GET['img'];
}else{
return error('404','请勿直接访问');
}
if (isset($file) && $file != "") {
include 'sina_config.php';
$cookie = $config['cookie'];
echo upload($file, $multipart,$cookie);
}else{
return error('201','上传错误');
} function CookieSet($cookie,$time){
$newConfig = '<?php
$config = array(
"cookie" => "'.$cookie.'",
"time" => "'.$time.'",
);';
@file_put_contents('sina_config.php', $newConfig);
} function error($code,$msg){
$arr = array('code'=>$code,'msg'=>$msg);
echo json_encode($arr);
}
/**
* 新浪微博登录(无加密接口版本)
* @param string $u 用户名
* @param string $p 密码
* @return string 返回最有用最精简的cookie
*/
function login($u,$p){
$loginUrl = 'https://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.4.15)&_=1403138799543';
$loginData['entry'] = 'sso';
$loginData['gateway'] = '1';
$loginData['from'] = 'null';
$loginData['savestate'] = '30';
$loginData['useticket'] = '0';
$loginData['pagerefer'] = '';
$loginData['vsnf'] = '1';
$loginData['su'] = base64_encode($u);
$loginData['service'] = 'sso';
$loginData['sp'] = $p;
$loginData['sr'] = '1920*1080';
$loginData['encoding'] = 'UTF-8';
$loginData['cdult'] = '3';
$loginData['domain'] = 'sina.com.cn';
$loginData['prelt'] = '0';
$loginData['returntype'] = 'TEXT';
return loginPost($loginUrl,$loginData);
} /**
* 发送微博登录请求
* @param string $url 接口地址
* @param array $data 数据
* @return json 算了,还是返回cookie吧//返回登录成功后的用户信息json
*/
function loginPost($url,$data){
$tmp = '';
if(is_array($data)){
foreach($data as $key =>$value){
$tmp .= $key."=".$value."&";
}
$post = trim($tmp,"&");
}else{
$post = $data;
}
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_HEADER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$post);
$return = curl_exec($ch);
curl_close($ch);
return 'SUB' . getSubstr($return,"Set-Cookie: SUB",'; ') . ';';
} /**
* 取本文中间
*/
function getSubstr($str,$leftStr,$rightStr){
$left = strpos($str, $leftStr);
//echo '左边:'.$left;
$right = strpos($str, $rightStr,$left);
//echo '<br>右边:'.$right;
if($left <= 0 or $right < $left) return '';
return substr($str, $left + strlen($leftStr), $right-$left-strlen($leftStr));
} function upload($file, $multipart = true,$cookie) {
$url = 'http://picupload.service.weibo.com/interface/pic_upload.php'.'?mime=image%2Fjpeg&data=base64&url=0&markpos=1&logo=&nick=0&marks=1&app=miniblog';
if($multipart) {
$url .= '&cb=http://weibo.com/aj/static/upimgback.html?_wv=5&callback=STK_ijax_'.time();
if (class_exists('CURLFile')) { // php 5.5
$post['pic1'] = new \CURLFile(realpath($file));
} else {
$post['pic1'] = '@'.realpath($file);
}
} else {
$post['b64_data'] = base64_encode(file_get_contents($file));
}
// Curl提交
$ch = curl_init($url);
curl_setopt_array($ch, array(
CURLOPT_POST => true,
CURLOPT_VERBOSE => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array("Cookie: $cookie"),
CURLOPT_POSTFIELDS => $post,
));
$output = curl_exec($ch);
curl_close($ch);
// 正则表达式提取返回结果中的json数据
preg_match('/({.*)/i', $output, $match);
if(!isset($match[1])) return error('201','上传错误');
$a=json_decode($match[1],true);
$width = $a['data']['pics']['pic_1']['width'];
$size = $a['data']['pics']['pic_1']['size'];
$height = $a['data']['pics']['pic_1']['height'];
$pid = $a['data']['pics']['pic_1']['pid'];
if(!$pid){return error('201','上传错误');}
$arr = array('code'=>'200','width'=>$width,"height"=>$height,"size"=>$size,"pid"=>$pid,"url"=>"http://ws3.sinaimg.cn/thumb150/".$pid.".jpg");
return json_encode($arr);
}

js代码:

/**
* @act 新浪图床上传
* @version 1.0
* @author youngxj
* @date <?php echo date("Y-m-d");?>
* @url http://www.youngxj.cn
*/ $(document).ready(function() {
$("input[type='file']").change(function(e) {
images_upload(this.files)
});
var obj = $('body');
obj.on('dragenter', function(e) {
e.stopPropagation();
e.preventDefault()
});
obj.on('dragover', function(e) {
e.stopPropagation();
e.preventDefault()
});
obj.on('drop', function(e) {
e.preventDefault();
images_upload(e.originalEvent.dataTransfer.files)
})
});
//远程上传
var url_upload = function() {
var urls = $("#urls").val();
var url_arr = urls.split("\n");
if (urls == "" || url_arr.length == 0) {
layer.alert("请贴入需要上传的网络图片地址.");
return;
}
$('#url_upload_model').modal('hide');
$('.mselector > button')[1].innerHTML = '上传中';
for (var i = 0; i < url_arr.length; i++) {
$.ajax({
url: 'https://api.yum6.cn/sinaimg.php',
type: 'GET',
data: {
img: url_arr[i]
},
cache: false,
dataType: 'json',
success: function(data) {
layer.msg('上传中');
if (typeof data.pid != 'undefined') {
$('#url-res-txt').append('https://ws3.sinaimg.cn/large/'+data.pid + '.jpg\n');
$('.mselector > button')[1].innerHTML = '成功 ' + (i + 1) + '/' + url_arr.length;
var apc = "<img src='" + data.url + "' alt='" + data.url + "'><p><a id='copy' data-clipboard-target='#copy' href='#' title='点击复制链接'>https://ws3.sinaimg.cn/large/" + data.pid + ".jpg</a></p><br>";
$('.preview').css('display', 'block');
$(".preview>hr").after(apc)
} else {
$('.mselector > button')[1].innerHTML = '第' + (i + 1) + '张上传失败'
} if (typeof data.pid != 'undefined') {
$('.mselector > button')[1].innerHTML = '上传成功'
} else {
$('.mselector > button')[1].innerHTML = '上传失败';
$('#url-res-txt').append(data.code + '\n');
layer.alert(data.code)
}
},
error: function(XMLResponse) {
layer.alert("error:" + XMLResponse.responseText)
}
})
}
};
//本地上传
var images_upload = function(files) {
var flag = 0;
$('textarea').empty();
$(files).each(function(key, value) {
$('.mselector > button')[0].innerHTML = '上传中';
image_form = new FormData();
image_form.append('file', value);
$.ajax({
url: 'https://api.yum6.cn/sinaimg.php?type=multipart', //此处填写API地址,这个地址是原作者提供调用,可以直接使用无问题
type: 'POST',
data: image_form,
mimeType: 'multipart/form-data',
contentType: false,
cache: false,
processData: false,
dataType: 'json',
success: function(data) {
flag++;
if (typeof data.url != 'undefined') {
$('#url-res-txt').append('https://ws3.sinaimg.cn/large/'+data.pid + '.jpg\n');
$('.mselector > button')[0].innerHTML = '成功 ' + flag + '/' + files.length;
var apc = "<img src='" + data.url + "' alt='" + data.url + "'><p><a id='copy"+ flag +"' data-clipboard-target='#copy"+ flag +"' href='#' title='点击复制链接' >https://ws3.sinaimg.cn/large/" + data.pid + ".jpg</a></p><br>";
$('.preview').css('display', 'block');
$(".preview>hr").after(apc)
} else {
$('.mselector > button')[0].innerHTML = '第' + flag + '张上传失败'
} if (flag == $("input[type='file']")[0].files.length) {
if (typeof data.url != 'undefined') {
$('.mselector > button')[0].innerHTML = '上传成功'
} else {
$('.mselector > button')[0].innerHTML = '上传失败';
$('#url-res-txt').append(data.code + '\n');
layer.alert(data.code)
}
}
},
error: function(XMLResponse) {
layer.alert("error:" + XMLResponse.responseText)
}
})
})
};
document.onpaste = function(e) {
var data = e.clipboardData;
for (var i = 0; i < data.items.length; i++) {
var item = data.items[i];
if (item.kind == 'file' && item.type.match(/^image\//i)) {
var blob = item.getAsFile();
images_upload(blob)
}
}
} //复制
var clipboard = new ClipboardJS('a');
clipboard.on('success',function(e){
e.clearSelection();
layer.msg('复制成功!');
});
clipboard.on('error',function(e){
e.clearSelection();
layer.msg('复制失败!');
});

html代码:

 <div class="container clearfix">
<div class="panel panel-default">
<div class="panel-heading">新浪图床外链<small class="text-capitalize">-Sina Img</small></div>
<div class="panel-body">
<div class="text-center">
<div class="mselector">
<input type="file" accept="image/*" multiple="">
<button type="button" class="btn btn-primary">选择本地图片</button>
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#url_upload_model">上传远程图片</button>
</div>
<hr/> <textarea id="url-res-txt" class="form-control" rows="5" placeholder="上传后的图片外链地址将显示在此处哦、下方会同时显示外链地址和预览图。" ></textarea>
<div class="preview">
<hr/>
</div>
<div id="url_upload_model" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">上传远程图片</h4>
</div>
<div class="modal-body">
<p class="lead">请在下方输入远程图片地址~每行一个~</p>
<textarea class="form-control" name="urls" rows="3" id="urls"></textarea>
<p id="urlUploadNotice"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" onclick="url_upload();">上传</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="sinaimg.js"></script>

另外还有一个html网页,现成的,复制到本地打开就行:

 <!DOCTYPE html>
<html lang='zh-cn'>
<head>
<meta charset='UTF-8'>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
<title>免费多图床</title> <link rel='stylesheet' href='https://cdn.bootcss.com/normalize/5.0.0/normalize.min.css'>
<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
<style>
html,body {height: 100%;margin: 0;padding: 0;}body {font-family: 'lucida grande', 'lucida sans unicode', lucida, helvetica, 'Hiragino Sans GB', 'Microsoft YaHei', 'WenQuanYi Micro Hei', sans-serif;align-items: center;display: flex;}a{text-decoration:none;}#container {max-width: 400px;flex-basis: 100%;margin: 0 auto;background: #FFF;border-radius: 10px;box-shadow: 0 0 30px rgba(0, 0, 0, 0.3);-webkit-box-shadow: 0 0 30px rgba(0, 0, 0, 0.3);overflow: hidden;}#container #hero-img {width: 100%;height: 200px;background: #007bff;}#container #profile-img {width: 160px;height: 160px;margin: -80px auto 0 auto;}#container #profile-img img {width: 100%;background: #FFF;border-radius: 50%;}#container #content {text-align: center;width: 320px;margin: 0 auto;padding: 0 0 50px 0;}#container #content h1 {font-size: 29px;font-weight: 500;margin: 30px 0 0 0;}#container #content p {font-size: 18px;font-weight: 400;line-height: 1.4;color: #666;margin: 15px 0 40px 0;}#container #content a {color: #CCC;font-size: 14px;margin: 0 10px;transition: color .3s ease-in-out;-webkit-transition: color .3s ease-in-out;line-height: 40px;}#container #content a:hover {color: #007bff;}.btn{background: none repeat scroll 0 0 #1BA1E2; border: 0 none; border-radius: 2px; color: #FFFFFF !important; cursor: pointer; font-family: "Open Sans","Hiragino Sans GB","Microsoft YaHei","WenQuanYi Micro Hei",Arial,Verdana,Tahoma,sans-serif; font-size: 14px; padding: 6px 10%;}.btn:hover,.yanshibtn:hover{background: none repeat scroll 0 0 #9B59B6; border: 0 none; border-radius: 2px; color: #FFFFFF!important; cursor: pointer; font-family: "Open Sans","Hiragino Sans GB","Microsoft YaHei","WenQuanYi Micro Hei",Arial,Verdana,Tahoma,sans-serif; font-size: 14px; padding: 8px 10%;}
.imgType{display: none;}
#images img{width: 100%}
#imgurl input{width: 100%}
#imgurl,#progress{display: none;} @-webkit-keyframes rotation{
from {-webkit-transform: rotate(0deg);}
to {-webkit-transform: rotate(360deg);}
} .Rotation{
-webkit-transform: rotate(360deg);
animation: rotation 3s linear infinite;
-moz-animation: rotation 3s linear infinite;
-webkit-animation: rotation 3s linear infinite;
-o-animation: rotation 3s linear infinite;
} .img{border-radius: 250px;}
</style>
</head>
<body>
<div id='container'> <div id='profile-img'>
<img src='' id="imgLoading" class="Rotation img" title=""/>
</div>
<div id='content'> <div id="progress"><progress max="100" value="0" id="pg"></progress></div>
<p class="imgType" id="imgType"></p>
<form id="form1">
<a href='javascript:void(0)' id="baiduImg" onclick="update('baidu')" class="btn btn-default" rel='nofollow'>百度图床(有效无https)</a><a href='javascript:void(0)' id="SinaImg" onclick="update('sina')" class="btn btn-default" rel='nofollow'>新浪图床(正常https)</a>
<a href='javascript:void(0)' id="sougouImg" onclick="update('sougou')" class="btn btn-default" rel='nofollow'>搜狗图床(失效)</a><a href='javascript:void(0)' id="soImg" onclick="update('so')" class="btn btn-default" rel='nofollow'>360 图床(失效)</a>
<input type="file" id="file" name="file" onchange="sc($('#imgType').attr('imgType'));" style="display:none" accept="image/*">
</form>
<div class="imgContent" id="imgContent">
<div id="images"></div>
<div id="imgurl">
<code>ImgUrl:</code>
<input onclick="oCopy(this)" value="" id="Imgs_url">
<code>HtmlUrl:</code>
<input onclick="oCopy(this)" value="" id="Imgs_html">
<code>Ubb:</code>
<input onclick="oCopy(this)" value="" id="Imgs_Ubb">
<code>Markdown:</code>
<input onclick="oCopy(this)" value="" id="Imgs_markdown">
</div>
</div> </div>
</div>
</body>
<script type="text/javascript"> function update(type){
$('#file').val('');
$('#imgType').attr({
imgType: type,
});
file.click(); } function sc(type){
if(!type){return false;}
var animateimg = $("#file").val();
$('#pg').val('0');
var imgarr=animateimg.split('\\');
var myimg=imgarr[imgarr.length-1];
var houzui = myimg.lastIndexOf('.');
var ext = myimg.substring(houzui, myimg.length).toUpperCase();
var file = $('#file').get(0).files[0];
if(!file){return false;}
var fileSize = file.size; switch(type){
case 'sougou':
var maxSize = 2097152;
break;
case 'baidu':
var maxSize = 2097152;
break;
case 'so':
var maxSize = 2097152;
break;
case 'sina':
var maxSize = 10485760;
break;
default:
var maxSize = 10485760;
}
if(ext !='.PNG' && ext !='.GIF' && ext !='.JPG' && ext !='.JPEG' && ext !='.BMP'){
parent.alert('文件类型错误,请上传图片类型');return false;
}else if(parseInt(fileSize) >= parseInt(maxSize)){
parent.alert('上传的文件不能超过'+maxSize/1024/1024+'MB');return false;
}else{
$('#imgLoading').attr('src','');
var data = new FormData($('#form1')[0]);
var YoungxjApisToken = 'f07b711396f9a05bc7129c4507fb65c5';
switch(type){
case 'sougou':
var apiUrl = 'https://apis.yum6.cn/api/5bd7f16aa33d7';
break;
case 'baidu':
var apiUrl = 'https://apis.yum6.cn/api/5bd828881f92b';
break;
case 'so':
var apiUrl = 'https://apis.yum6.cn/api/5bd90750c3f77';
break;
case 'sina':
var apiUrl = 'https://apis.yum6.cn/api/5bd44dc94bcfc';
break;
default:
return false;
};
$('#progress').show();
$.ajax({
url: apiUrl+'?token='+YoungxjApisToken,
type: 'POST',
data: data,
dataType: 'JSON',
processData: false,
contentType: false,
xhr: function(){
var xhr = $.ajaxSettings.xhr();
if(onprogress && xhr.upload) {
xhr.upload.addEventListener("progress" , onprogress, false);
return xhr;
}
}
}).done(function(ret){
if(ret['code']=='1'){ var img = '';var imgurl = '';
if(type!='sina'){var imgSrc = ret['data'];}else{var imgSrc = ret['data']['url'];}
img += '<img src="'+imgSrc+'" name="sinaimg" id="sinaimg">'; $('#Imgs_url').val(imgSrc);
$('#Imgs_html').val('<img src="'+imgSrc+'"/>');
$('#Imgs_Ubb').val('[img]'+imgSrc+'[/img]');
$('#Imgs_markdown').val('![]('+imgSrc+')');
$('#images').html(img);$('#imgLoading').attr('src','');
$('#imgurl').show();
$('#progress').hide();
}else{
$('#progress').hide();
$('#imgLoading').attr('src','');
parent.alert(ret['msg']);
} });
return false;
}
} function onprogress(evt){
var loaded = evt.loaded;
var tot = evt.total;
var per = Math.floor(100*loaded/tot);
$('#pg').val(per); }
function oCopy(obj){
obj.select();
document.execCommand("Copy");
if (browserRedirect()) {alert('设备类型为手机,有一定几率复制失败!请查看剪切板是否成功复制');}
} function browserRedirect(){
var sUserAgent = navigator.userAgent.toLowerCase();
var bIsIpad = sUserAgent.match(/ipad/i) == 'ipad';
var bIsIphone = sUserAgent.match(/iphone os/i) == 'iphone os';
var bIsMidp = sUserAgent.match(/midp/i) == 'midp';
var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == 'rv:1.2.3.4';
var bIsUc = sUserAgent.match(/ucweb/i) == 'web';
var bIsCE = sUserAgent.match(/windows ce/i) == 'windows ce';
var bIsWM = sUserAgent.match(/windows mobile/i) == 'windows mobile';
var bIsAndroid = sUserAgent.match(/android/i) == 'android';
if(bIsIpad || bIsIphone || bIsMidp || bIsUc7 || bIsUc || bIsCE || bIsWM || bIsAndroid ){
return 1;
}
};
$(document).ready(function(){
$('#imgLoading').click(function() {$("#imgContent").toggle();});
});
</script>
</html>

作者博客地址:https://www.youngxj.cn

文中JS链接地址:https://blog-static.cnblogs.com/files/vanwee/sinaimg.js

新浪微博已经限制外链

友情链接:

上海网站制作

上一篇:8天掌握EF的Code First开发系列之2 Code First开发系列之领域建模和管理实体关系


下一篇:Code First开发系列之领域建模和管理实体关系