如何在typora插入图片并上传到自己的服务器(图床)

38 阅读1分钟

如何在typora插入图片并上传到自己的服务器(图床)

1.在腾讯云上配置宝塔镜像

版本如下

Nginx + PHP≥7.0 + linux

image.png

2.在宝塔中选择下载安装图床

image.png

选择左侧的“文件”删掉其中的user.ini文件

3.开启api

​ 进入你的图床->设置->图床安全

​ 打开api上传

image.png

4.在typora中配置

​ 文件->偏好设置->图像

配置如下:

image.png

命令:

​ 地址替换你自己的js文件所在地址即可

node E:\scripts\typora\uploadImage.js

4.js脚本编写

图床API地址:设置->API设置->API调用地址

token地址:设置->API设置->Token API 管理

image.png

代码:

const fetch = require('node-fetch');
const fs = require('fs');
const path = require('path');
const FormData = require('form-data');
const { log } = require('console');

const uploadUrl = 'XXX';//替换你图床的API地址
const token = 'xxx';//替换为你的token

async function uploadImage(filePath) {
    const formData = new FormData();
    formData.append('image', fs.createReadStream(filePath));
    formData.append('token', token);

    try {
        const response = await fetch(uploadUrl, {
            method: 'POST',
            body: formData
        });

        const result = await response.json();
        if (result) {
            console.log(result.url);
        } else {
            console.error('Upload failed:', result);
        }
    } catch (error) {
        console.error('Error:', error);
    }
}
// 删除本地保存文件的函数,可以不写
function deleteFile(filePath) {
    fs.unlink(filePath, (err) => {
        if (err) {
            console.error(`删除文件时出错: ${err.message}`);
            return;
        }
        console.log(`文件 ${filePath} 已成功删除。`);
    });
}
const filePath = process.argv[2];
const normalizedPath = path.normalize(filePath);
if (filePath) {
    uploadImage(filePath);
    deleteFile(normalizedPath);
} else {
    console.error('Please provide a file path');
}

其中的deleteFile函数是为了删掉本地存储的图片,只用图床的,如果想要本地也保存,请删掉这个函数。

[!NOTE]

对于返回的url要console.log,而不是return。

图床对应代码仓库地址:github.com/icret/EasyI…

可以去支持一波作者(反正我是支持了)!!💕👍👍