Skip to content

Commit

Permalink
feat: #132 集成PicGO以及图床-非electron环境支持剪贴板上传
Browse files Browse the repository at this point in the history
  • Loading branch information
terwer committed Dec 28, 2022
1 parent b224ab1 commit b6dea35
Show file tree
Hide file tree
Showing 5 changed files with 139 additions and 9 deletions.
40 changes: 39 additions & 1 deletion components/picgo/PicgoIndex.vue
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ import { ElMessage } from "element-plus"
import { useI18n } from "vue-i18n"
import { uploadByPicGO } from "~/utils/otherlib/picgoUtil"
import { reactive, ref } from "vue"
import { inSiyuan } from "~/utils/platform/siyuan/siyuanUtil"
import { isInSiyuanNewWinBrowser } from "~/utils/otherlib/siyuanBrowserUtil"
const logger = LogFactory.getLogger("components/picgo/PicgoIndex.vue")
const { t } = useI18n()
Expand Down Expand Up @@ -126,22 +128,58 @@ const doAfterUpload = (imgInfos) => {
ElMessage.success(t("main.opt.success"))
}
const readBase64FromFile = async (file) => {
const reader = new FileReader()
reader.readAsDataURL(file)
const base64 = await new Promise((resolve, reject) => {
reader.onload = () => resolve(reader.result)
reader.onerror = (error) => reject(error)
})
return base64
}
const onRequest = async (event) => {
isUploadLoading.value = true
try {
const fileList = event.target.files
console.log("onRequest fileList=>", fileList)
if (!fileList || fileList.length === 0) {
ElMessage.error("请选择图片")
isUploadLoading.value = false
return
}
if (!inSiyuan() && !isInSiyuanNewWinBrowser()) {
ElMessage.error("非electron环境只能通过剪贴板上传")
isUploadLoading.value = false
return
}
// 获取选择的文件的路径数组
const filePaths = []
for (let i = 0; i < fileList.length; i++) {
filePaths.push(fileList.item(i).path)
// const tmppath = URL.createObjectURL(fileList[i])
// logger.debug("tmppath=>", tmppath)
//
// const base64 = await readBase64FromFile(fileList[i])
// logger.debug("base64=>", base64)
if (fileList.item(i).path) {
filePaths.push(fileList.item(i).path)
logger.debug("路径不为空")
} else {
// const base64Obj = {
// base64Image: base64,
// fileName: fileList.item(i).name, // 图片的文件名
// width: "200", // 图片宽度
// height: "200", // 图片高度
// extname: ".png", // 图片格式的扩展名 比如.jpg | .png
// }
logger.debug("路径为空,忽略")
// filePaths.push(base64Obj)
}
}
const imgInfos = await uploadByPicGO(filePaths)
Expand Down
7 changes: 7 additions & 0 deletions utils/browserUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ import { fileOpen, FileWithHandle } from "browser-fs-access"
export const isBrowser = (): boolean =>
typeof window !== "undefined" && typeof window.document !== "undefined"

/**
* 检测是否是本地请求
* @param apiUrl 请求地址
*/
export const isLocalhost = (apiUrl: string): boolean =>
apiUrl.indexOf("127.0.0.1") > -1 || apiUrl.indexOf("localhost") > -1

/**
* 获取url参数
* @param sParam 参数
Expand Down
8 changes: 6 additions & 2 deletions utils/otherlib/picgoUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
*/

import { isInSiyuanNewWinBrowser } from "~/utils/otherlib/siyuanBrowserUtil"
import { PicGoUploadApi } from "~/utils/platform/picgo/picGoUploadApi"

// Pico上传Api封装
const picGoUploadApi = new PicGoUploadApi()

/**
* 通过PicGO上传图片,主窗口
Expand All @@ -49,13 +53,13 @@ export async function uploadByPicGO(input) {
if (isInSiyuanNewWinBrowser()) {
return uploadNewWinByPicGO(input)
} else {
alert("aaa")
return picGoUploadApi.upload(input)
}
} else {
if (isInSiyuanNewWinBrowser()) {
return uploadNewWinClipboardByPicGO()
} else {
alert("bbb")
return picGoUploadApi.upload()
}
}
}
Expand Down
22 changes: 16 additions & 6 deletions utils/platform/commonblog/commonblogApi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import {
sendChromeMessage,
} from "~/utils/otherlib/ChromeUtil"
import { getWidgetId } from "~/utils/platform/siyuan/siyuanUtil"
import { isEmptyString } from "~/utils/util"
import { isLocalhost } from "~/utils/browserUtil"

export class CommonblogApi {
protected logger: Logger
Expand Down Expand Up @@ -135,8 +137,11 @@ export class CommonblogApi {
): Promise<any> {
let result

const widgetResult = getWidgetId()
if (widgetResult.isInSiyuan) {
if (isLocalhost(apiUrl)) {
this.logger.warn("检测到本地请求,直接fetch获取数据")
// 不解析了,直接fetch
result = await fetch(apiUrl, fetchOptions)
} else if (getWidgetId().isInSiyuan) {
this.logger.warn("当前处于挂件模式,使用electron的fetch获取数据")
// 不解析了,直接使用Node兼容调用
result = await fetch(apiUrl, fetchOptions)
Expand Down Expand Up @@ -219,16 +224,21 @@ export class CommonblogApi {
throw new Error("请求内容过多,请删减文章正文之后再试")
}

const msg = response.statusText
let msg = response.statusText
if (isEmptyString(msg)) {
msg = "网络超时或者服务器错误,请稍后再试。"
} else {
msg = "错误信息:" + msg
}
throw new Error(msg)
} else {
throw new Error("fetch请求错误")
}
}

const widgetResult = getWidgetId()

if (widgetResult.isInSiyuan) {
if (isLocalhost(apiUrl)) {
resJson = await response.json()
} else if (getWidgetId().isInSiyuan) {
resJson = await response.json()
} else {
const corsJson = await response.json()
Expand Down
71 changes: 71 additions & 0 deletions utils/platform/picgo/picGoUploadApi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { CommonblogApi } from "~/utils/platform/commonblog/commonblogApi"
import { isEmptyObject } from "~/utils/util"

/**
* PicGO上传Api
* @since 0.6.0
* @author terwer
*/
export class PicGoUploadApi extends CommonblogApi {
/**
* 上传图片到PicGO
* @param input 路径数组,可为空,为空上传剪贴板
*/
public async upload(input?: any[]): Promise<string> {
let ret = JSON.stringify([])

const apiUrl = "http://127.0.0.1:36677/upload"

const fetchOps = {
method: "POST",
}

let data
// 传递了路径,上传具体图片,否则上传剪贴板
if (input) {
data = { list: input }
}

// 数据不为空才传递
if (!isEmptyObject(data)) {
Object.assign(fetchOps, {
body: JSON.stringify(data),
})
}

Object.assign(fetchOps, {
headers: {
"Content-Type": "application/json",
"User-Agent": "Terwer/0.1.0",
},
})

// 发送请求
this.logger.debug("调用HTTP请求上传图片到PicGO,apiUrl=>", apiUrl)
this.logger.debug("调用HTTP请求上传图片到PicGO,fetchOps=>", fetchOps)

// 使用兼容的fetch调用并返回统一的JSON数据
const resJson = await this.doFetch(apiUrl, fetchOps)
this.logger.debug("resJson=>", JSON.stringify(resJson))
// this.logger.debug("resJson", resJson)

if (resJson.success) {
const rtnArray = []
if (resJson.result && resJson.result.length > 0) {
resJson.result.forEach((img) => {
const rtnItem = {
fileName: img.substring(img.lastIndexOf("/") + 1),
imgUrl: img,
}
rtnArray.push(rtnItem)
})
}

ret = JSON.stringify(rtnArray)
} else {
throw new Error("调用HTTP上传到PicGO失败,请检查配置=>" + resJson.message)
}

return Promise.resolve(ret)
}
}

0 comments on commit b6dea35

Please sign in to comment.