javascript - 面临向对象 JS 添加属性的问题
问题描述
我正在尝试将属性添加到文件对象。我正在添加这样的属性(我正在使用 Vue):
<input type="file" id="fileUpload" name="file" @change="setToUploadStatus" multiple>
setToUploadStatus 方法:
setToUploadStatus (event) {
let files = event.target.files
Array.from(files).forEach((file) => {
let id = this.randomString(10)
file.id = id
this.uploadStatus.push({
id: id,
name: file.name,
uploading: false,
uploaded: false
})
}
this.uploadFile(files)
}
上传文件方法:
async uploadFile (files) {
for (const file of files) {
// Upload file with axios
}
}
随机字符串方法:
randomString (length) {
let text = ''
let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
我的问题是它并不id
总是添加属性。有时它会添加有时不会。Specially when many files are selected. 这是一个日志https://prnt.sc/kxsqhi
我究竟做错了什么?请帮忙!
在此处转换为片段:
setToUploadStatus(event) {
let files = event.target.files
Array.from(files).forEach((file) => {
let id = this.randomString(10)
file.id = id
this.uploadStatus.push({
id: id,
name: file.name,
uploading: false,
uploaded: false
})
}
this.uploadFile(files)
}
async uploadFile(files) {
for (const file of files) {
// Upload file with axios
}
}
randomString(length) {
let text = ''
let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
<input type="file" id="fileUpload" name="file" @change="setToUploadStatus" multiple>
解决方案
首先,从您提供的代码来看,它没有任何问题。也许问题来自其他地方。
其次,我看到您想为id
每个文件赋予唯一性。生成随机字符串很好,但仍然有可能两个random
字符串相同。所以这里有一个简单的方法来解决这个问题。
new Vue({
el: "#app",
data: {},
methods: {
updateFile(event) {
let files = event.target.files
let uid = 0;
Array.from(files).forEach(file => {
file.id = ++uid;
console.log(file);
});
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<input type="file" multiple @input="updateFile" />
</div>
这个实现很简单。
这是 JSFiddle 链接:https ://jsfiddle.net/clintonyeb/3qreb1L9/
推荐阅读
- mysql - 尝试创建表时出现 MySQL 错误,
- php - 来自mysql数据库的android-plot条形图
- javascript - 违反以下内容安全策略指令
- api - 如何通过赛普拉斯的 API 在我的数据库中创建/删除项目?
- html - 身体元素在身体之外
- android - android以编程方式将自定义值设置为自定义文本视图
- python - 如何在没有高级模型功能的情况下使用 keras 层进行训练和预测
- c++ - 具有源和目标的无向图上的 BOOST min-cut/max-flow
- visual-studio-code - 配置 VSCode 包含路径
- java - 如何将此 curl 请求转换为 Http post 请求以在 java 中上传文件?