javascript - 如何在 html 中选择文件并在 javascript 中管理它
问题描述
我需要在 html 中选择一个 .csv 文件并使用 javascript 对其进行管理(我需要将其转换为 JSON),我做了一些事情但效果不佳。
要在 html 中选择一个文件,我这样做了:
<input id="inputFile" accept=".csv" type="file"> <br>
<br>
<input value="Send" type="button" onclick="showFile()">
<label id="mylabel">
</label>
<script src="../javascript/parseFileScript.js"></script>
为了管理它,我这样做了:
//take a string containing a csv
function csvJSON(csv){
console.log(typeof csv)
var lines=csv.split("\n");
var result = [];
// NOTE: If your columns contain commas in their values, you'll need
// to deal with those before doing the next step
// (you might convert them to &&& or something, then covert them back later)
// jsfiddle showing the issue https://jsfiddle.net/
var headers=lines[0].split(",");
for(var i=1;i<lines.length;i++){
var obj = {};
var currentline=lines[i].split(",");
for(var j=0;j<headers.length;j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
//return result; //JavaScript object
return JSON.stringify(result); //JSON
}
//load the selected file and convert in string
async function getCSV() {
let file = document.getElementById('inputFile').files[0];
console.log(typeof file)
let text = await file.text();
return text;
}
//put the body of the selected file in a label
function showFile() {
let csv = getCSV();
let json = csvJSON(csv);
document.getElementById('mylabel').innerHTML = json;
}
我得到的错误是Uncaught TypeError: csv.split is not a function
,所以我检查函数 csvJSON 中的 csv 类型和 getCSV 中的文件类型,在这两种情况下,控制台都告诉我类型是对象。
有人可以向我解释我错在哪里以及如何解决问题吗?
解决方案
推荐阅读
- python - 我无法使用常用的网络抓取工具从网站上抓取表格
- flutter - 如何将我的 VIsual Studio Code 构建的应用程序发布为 APK?
- flutter - 如何在滑块 FLUTTER 中执行操作
- java - 冒泡排序 String 数组和 int 数组
- sql - 在 DataStudio 的 SQL 查询中使用 timestamp_trunc 中的参数
- node.js - 将 setTimeout 用于 Discord 机器人响应延迟和自定义“正在输入”
- node.js - 设置 Redis cookie 时,Apollo 客户端未连接到服务器
- python - 将 Class 方法应用于 Class 列表中的所有 Class 方法
- xml - 为什么必须在 XML 属性中转义 <?
- javascript - Condition 用初始值检查 Redux state