首页 > 解决方案 > 如何在 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 中的文件类型,在这两种情况下,控制台都告诉我类型是对象。

有人可以向我解释我错在哪里以及如何解决问题吗?

标签: javascripthtml

解决方案


推荐阅读