Skip to content

Commit 7fe1be3

Browse files
committed
feat: 重构图片下载
1 parent 176ac9c commit 7fe1be3

3 files changed

Lines changed: 33 additions & 23 deletions

File tree

dist/index.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

dist/preview.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/uploader.ts

Lines changed: 31 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -299,37 +299,47 @@ async function uploadRemoteImage(params: {
299299
)
300300

301301
try {
302-
let url = params.src
303-
const queryParams: { url?: string } = {}
304-
const sp = params.src.substr(0, 5).toLowerCase()
305-
if (sp !== window.location.protocol && sp.startsWith('http')) {
306-
queryParams.url = params.src
307-
url = `${apiV2BaseUrl.replace(/\/+$/, '')}/proxy-request`
308-
}
302+
const contentType = 'image/png'
303+
const filename = `${Date.now()}.png`
304+
const { blob, file, buff } = await new Promise((resolve, reject) => {
305+
const img = document.createElement('img')
306+
img.addEventListener('load', () => {
307+
console.log('here')
308+
const canvas = document.createElement('canvas')
309+
canvas.setAttribute('width', `${params.width}`)
310+
canvas.setAttribute('height', `${params.height}`)
309311

310-
const { headers, data } = await axios.get(url, {
311-
responseType: 'arraybuffer',
312-
params: queryParams,
313-
})
312+
const ctx = canvas.getContext('2d')!
313+
ctx.drawImage(img, 0, 0, params.width, params.height)
314314

315-
const contentType = (headers['content-type'] || '').toLowerCase().trim()
316-
if (!data || data.byteLength <= 0 || !contentType || !contentType.startsWith('image/')) {
317-
throw new Error()
318-
}
315+
canvas.toBlob(blob => {
316+
if (!blob) {
317+
return reject()
318+
}
319+
const reader = new FileReader()
320+
reader.addEventListener('load', () => {
321+
const buff = reader.result as ArrayBuffer
322+
const file = new File([blob], filename, { type: contentType })
323+
resolve({ blob, file, buff })
324+
})
325+
reader.addEventListener('error', () => reject())
326+
reader.readAsArrayBuffer(blob)
327+
}, contentType)
328+
})
329+
img.addEventListener('error', () => reject())
330+
img.crossOrigin = 'anonymous'
331+
img.src = params.src
332+
})
319333

320334
const spark = new Spark.ArrayBuffer()
321-
const hash = spark.append(data).end()
322-
const filename = `${Date.now()}.${contentType.substr(6)}`
323-
const file = new File([data], filename, {
324-
type: contentType,
325-
})
335+
const hash = spark.append(buff).end()
326336

327337
uploadFiles.set(id, {
328338
id,
329339
useCounter: 1,
330340
image: {
331341
file,
332-
buff: data,
342+
buff,
333343
hash,
334344
url: params.src,
335345
width: params.width,

0 commit comments

Comments
 (0)