背景
在使用cdsn导入大量md文档内容时无法导入本地文件,导致文档格式、和编写体验极差,经过大量查找文档,大部分人都是使用图床,免费的图床有使用giee(不知道是不是运气不好,等我用的时候已经加上图片防盗机制了)、sm.sm(看着比较麻烦,不知道效果如何)、自建服务(还是会出现转存失败问题),也有直接使用 <img src=“xxx”>不过会引起格式混乱。于是我不得不打起cdsn的主意,看了看cdsn的代码上传图片,然后。。。(希望不会被和谐)
csdn图片上传
第一步获取cdsn cookie
打开控制台输入:
document.cookie
第二步上代码
使用的是lavavel(什么框架都行),依赖是使用的guzzlehttp/guzzle
composer require guzzlehttp/guzzle
<?php
namespace Resources\lib;
use GuzzleHttp\Client;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Exception\GuzzleException;
class FileUpload
{
private static $instance = null;
// 禁止拷贝
/**
* @var Client
*/
private $client;
private $imageUri = 'https://imgservice.csdn.net';
private $cookie;
/**
* @var mixed
*/
private $ossParam;
private function __clone()
{
// TODO: Implement __clone() method.
}
// 禁止实例化
private function __construct()
{
$this->client = new Client();
}
/**
* @return self
*/
public static function getInstance(): self
{
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function setCookie($cookie)
{
$this->cookie = $cookie;
}
public function ossAccessId($suffix)
{
try {
$response = $this->client->get($this->imageUri . '/direct/v1.0/image/upload', [
'headers' => [
'cookie' => $this->cookie,
'Content-type' => 'application/json'
],
'query' => [
'type' => 'blog',
'rtype' => 'markdown',
'x-image-template' => 'standard',
'x-image-app' => 'direct_blog',
'x-image-dir' => 'direct',
'x-image-suffix' => $suffix
]
]);
$res = $response->getBody()->getContents();
$res = json_decode($res, true);
if ($res['code'] == 200) {
$this->ossParam = $res['data'];
return true;
} else {
return false;
}
} catch (GuzzleException $e) {
$this->ossParam = [];
}
return false;
}
public function fileUpload($file_name)
{
$fileInfo = getimagesize($file_name);
$multipart=[
[
'name' => 'key',
'contents' => $this->ossParam['filePath']
],
[
'name' => 'OSSAccessKeyId',
'contents' => $this->ossParam['accessId']
],
[
'name' => 'policy',
'contents' => $this->ossParam['policy']
],
[
'name' => 'Signature',
'contents' => $this->ossParam['signature']
],
[
'name' => 'callback',
'contents' => $this->ossParam['callbackUrl']
],
[
'name' => 'file',
'contents' => fopen($file_name, 'r'),
'headers'=>[
'Content-Disposition'=>'form-data; name="file"; filename="'.pathinfo($file_name, PATHINFO_BASENAME).'"',
'Content-Type'=> $fileInfo['mime']
]
]
];
try {
$response = $this->client->post($this->ossParam['host'], [
'multipart' =>$multipart
]);
$res = $response->getBody()->getContents();
$res=json_decode($res, true);
} catch (\GuzzleHttp\Exception\ClientException $e) {
$responseBody = $e->getResponse()->getBody()->getContents();
$res=[
'code'=>203,
'data'=>[],
'msg'=> $responseBody
];
}
return $res;
}
}
第三步调用
$cookie="你的cookie";
$file='/xxxx/0fba7793ab078a6b2faa102ac5677ac7.jpg';
$client= \Resources\lib\FileUpload::getInstance();
$client->setCookie($cookie);
$client->ossAccessId('jpeg');
//这里最好是加一个判断
$client->fileUpload($file);