Skip to content

Commit

Permalink
Merge pull request #306 from cnblogs/revert-upload-image-changes
Browse files Browse the repository at this point in the history
fix: revert upload-img changes
  • Loading branch information
cnblogs-dudu authored Oct 5, 2024
2 parents 98e2db1 + 8a0d051 commit babf62b
Show file tree
Hide file tree
Showing 4 changed files with 63 additions and 22 deletions.
2 changes: 1 addition & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
}
],
"@typescript-eslint/strict-boolean-expressions": [
"error",
"warn",
{
"allowString": false,
"allowNumber": false,
Expand Down
22 changes: 10 additions & 12 deletions src/cmd/upload-img/upload-img-from-path.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { readableToBytes } from '@/infra/convert/readableToBuffer'
import { Alert } from '@/infra/alert'
import { imageService } from '@/service/upload-img/image.service'
import fs from 'fs'
import { RsHttp } from '@/wasm'
import { getAuthedImgReq } from '@/service/extract-img/get-replace-list'

export async function uploadImgFromPath(path: string) {
const readable = fs.createReadStream(path)

const bytes = await readableToBytes(readable)
const req = await getAuthedImgReq()
const mime = RsHttp.mimeInfer(path)
if (mime === undefined) throw Error('未知的 MIME 类型')

return req.upload(bytes, mime)
export function uploadImgFromPath(path: string) {
try {
const readStream = fs.createReadStream(path)
return imageService.upload(readStream)
} catch (e) {
console.log(`上传图片失败: ${<string>e}`)
void Alert.err(`上传图片失败: ${<string>e}`)
}
}
14 changes: 5 additions & 9 deletions src/cmd/upload-img/upload-img.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,12 @@ export async function uploadImg() {

let imageUrl: string | undefined

try {
if (selected === options[0]) imageUrl = await uploadFsImage()
else if (selected === options[1]) imageUrl = await uploadClipboardImg()
if (selected === options[0]) imageUrl = await uploadFsImage()
else if (selected === options[1]) imageUrl = await uploadClipboardImg()

if (imageUrl === undefined) return
if (imageUrl === undefined) return

await showUploadSuccessModel(imageUrl)
await showUploadSuccessModel(imageUrl)

return imageUrl
} catch (e) {
void Alert.err(`上传图片失败: ${<string>e}`)
}
return imageUrl
}
47 changes: 47 additions & 0 deletions src/service/upload-img/image.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { Readable } from 'stream'
import { isString, merge, pick } from 'lodash-es'
import path from 'path'
import httpClient from '@/infra/http-client'
import { ExtConst } from '@/ctx/ext-const'

class ImageService {
async upload<T extends Readable & { name?: string; fileName?: string; filename?: string; path?: string | Buffer }>(
file: T
): Promise<string> {
// eslint-disable-next-line @typescript-eslint/naming-convention
const FormData = (await import('form-data')).default
const form = new FormData()
const { name, fileName, filename, path: _path } = file
const finalName = path.basename(isString(_path) ? _path : fileName || filename || name || 'image.png')

Check warning on line 15 in src/service/upload-img/image.service.ts

View workflow job for this annotation

GitHub Actions / node-lint

Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly

Check warning on line 15 in src/service/upload-img/image.service.ts

View workflow job for this annotation

GitHub Actions / node-lint

Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly

Check warning on line 15 in src/service/upload-img/image.service.ts

View workflow job for this annotation

GitHub Actions / node-lint

Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly
const ext = path.extname(finalName)
const mime = await import('mime')
const mimeType = mime.lookup(ext, 'image/png')
form.append('image', file, { filename: finalName, contentType: mimeType })
const response = await httpClient.post(`${ExtConst.ApiBase.BLOG_BACKEND}/posts/body/images`, {
body: form,
})

return response.body
}

/**
* Download the image from web
* This will reject if failed to download
* @param url The url of the web image
* @param name The name that expected applied to the downloaded image
* @returns The {@link Readable} stream
*/
async download(url: string, name?: string): Promise<Readable> {
const response = await httpClient.get(url, { responseType: 'buffer' })
const contentType = response.headers['content-type'] ?? 'image/png'
name = name ? 'image' : name

Check warning on line 37 in src/service/upload-img/image.service.ts

View workflow job for this annotation

GitHub Actions / node-lint

Unexpected nullable string value in conditional. Please handle the nullish/empty cases explicitly
const mime = await import('mime')

return merge(Readable.from(response.body), {
...pick(response, 'httpVersion', 'headers'),
path: `${name}.${mime.extension(contentType) ?? 'png'}`,
})
}
}

export const imageService = new ImageService()

0 comments on commit babf62b

Please sign in to comment.