当你只有图片路径url怎么上传呢?
// item为包含img片段,用getAsString转为string类型
await this.urlToFile(item, 'name'),then(file => {
this.upload(file)
}
urlToFile (item, fileName) {
const self = this
return new Promise(function (resolve, reject) {
try {
item.getAsString(function (str) {
const imageUrl = (str.match(/img src="(\S*)"/) || [])[1] || '' // 截取图片url
if (!imageUrl) {
self.$message.error('读取图片失败')
reject(new Error('读取图片失败'))
return
}
let image = new Image()
image.src = imageUrl
image.setAttribute('crossOrigin', 'anonymous') // 跨域
const imgPromise = new Promise(function (resolve, reject) {
image.onload = function () {
let canvas = document.createElement('canvas') // 创建canvas元素
const width = image.width // 确保canvas的尺寸和图片一样
const height = image.height
canvas.width = width
canvas.height = height
canvas.getContext('2d').drawImage(image, 0, 0, width, height) // 将图片绘制到canvas中
const dataURL = canvas.toDataURL('image/png') // 转换图片为dataURL
const arr = dataURL.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
const file = new File([u8arr], fileName, { type: mime })
resolve(file)
}
image.onerror = () => {
self.$message.error('读取图片失败')
reject()
}
})
imgPromise.then(file => {
resolve(file)
})
})
} catch (e) {
self.$message.error('读取图片失败')
reject()
}
})
}
upload(file) {
const params = new FormData
params.append('file', file)
this.$http.post('/upload', params).then(res => {})
}