文件上传-获取图像分辨率



我正在尝试获取发送到后端的图像的分辨率(高度、宽度(。注意,在本例中,几个图像同时发送到后端。所以,我们正在使用循环!

我试图在后台找到一个解决方案,但什么也找不到。这是我问的相应的stackoverflow问题。

现在我正在寻求一种在前端做到这一点的方法。当Iconsole.log(file)时,将输出以下示例:

lastModified: 1657671728196
lastModifiedDate: Wed Jul 13 2022 02:22:08 GMT+0200 (Mitteleuropäische Sommerzeit) {}
name: "Example.png"
size: 3128
type: "image/png"
webkitRelativePath: ""

遗憾的是,决议不能以这种方式提出。此外,我想将img类型保存在数据库中,但不保存为image/png,而仅保存为pngjpeg等。

async submitFiles() {
const formData = new FormData()
for (let i = 0; i < this.files.length; i++) {
const file = this.files[i]
formData.append('files', file)
console.log(file)
}
try {
const response = await this.$axios.post('/api/upload-files', formData, {
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
this.uploadPercentage = parseInt(
Math.round((progressEvent.loaded / progressEvent.total) * 100)
)
},
})
const result = response.data
if (result.success) {
if (this.uploadPercentage === 100) {
this.$nuxt.refresh()
this.$emit('exit', true)
}
}
} catch (err) {
console.log(err)
}
},

在浏览器中检查分辨率非常简单。您所需要做的就是从用户提供的文件中创建一个Image元素。

export default {
data() {
return {
files: [],
formData: null
}
},
watch: {
formData() {
if (this.formData.getAll('files').length === this.files.length) {
this.submitFiles()
}
},
},
mounted() {
this.formData = new FormData()
},
methods: {
async submitFiles() {
try {
const data = this.formData
const response = await this.$axios.post(
'/api/upload-files', data,
{
headers: { 'Content-Type': 'multipart/form-data' },
onUploadProgress: (progressEvent) => {
this.uploadPercentage = parseInt(
Math.round((progressEvent.loaded / progressEvent.total) * 100)
)
},
}
)
const result = response.data
if (result.success) {
if (this.uploadPercentage === 100) {
this.$nuxt.refresh()
this.$emit('exit', true)
}
}
} catch (err) {
console.log(err)
}
},
processFiles() {
for (let i = 0; i < this.files.length; i++) {
const file = this.files[i]
const img = new Image()
const vm = this
img.onload = function () {
file.width = this.width
file.height = this.height
console.log(file)
vm.formData.append('files', file)
}
img.src = URL.createObjectURL(file)
}
},
},
}

至于图像的mime类型,您可以通过/分割字符串并保存右半部分:

const [,type] = file.type.split('/')

编辑:当您尝试发布数据(在try块内(时,回调不会被调用,因此最好观察formData,直到它的长度与files数组的长度匹配。然后我们知道所有的图像都经过了处理,可以安全地将数据发送到我们的后端。

最新更新