简体   繁体   English

如何将上传的CSV文件传递到我的函数中?

[英]How do I pass an uploaded CSV file, into my function?

first of all, pardon me if this is not the correct way of asking a question but this is my first post. 首先,请原谅我,如果这不是提问的正确方法,但这是我的第一篇文章。

I am working on a university project and am new to JavaScript ( and subsequently, jQuery and NodeJS ). 我正在从事大学项目,不熟悉 JavaScript( 以及随后的jQuery和NodeJS )。 I am trying to make a system that will take a CSV file, process it and load the results into a database ready to be used by the rest of the system. 我正在尝试创建一个系统,该系统将采用CSV文件,处理它并将结果加载到数据库中,以供系统的其余部分使用。

I have made it so that I can upload the file to a directory and have a function to process the CSV file into a JSON object ( we have only just started to cover databases so I will have to modify this to store in the database ), but the problem I'm currently facing is this... 我已经做到这一点,我可以将文件上传到一个目录,并具有将CSV文件处理成JSON对象的功能( 我们刚刚开始覆盖数据库,所以我必须修改它以存储在数据库中 ),但我目前面临的问题是......

How do I pass/read the uploaded file into the function for processing? 如何将上传的文件传递/读入函数进行处理?

I have searched around and have found similar questions, but these are either usually using PHP or cover different aspects of my issue, without actually touching upon my problem. 我已经搜索过并发现了类似的问题,但这些问题通常都是使用PHP或涵盖我的问题的不同方面,而不是实际上触及我的问题。

I'm sorry if this is something very basic that I am missing, but I'm pulling my hair out over this and can't progress to the rest of the tasks until i have the first part in place - upload, process and store the CSV file. 我很抱歉,如果这是我缺少的一些非常基本的东西,但是我正在把头发拉出来,并且在第一部分到位之前不能进展到剩下的任务 - 上传,处理和存储CSV文件。

I will take any advice, either directly related to the issue or pointers from experience that you think I may face, and thank you for you time. 我会接受任何与此问题直接相关的建议或您认为我可能面临的经验指示,并感谢您抽出时间。

Upload 上传

 var express = require("express"); var multer = require("multer"); var fs = require("fs"); var path = require("path"); var app = express(); var upload = multer({ dest: './uploads/'}); app.use(express.static('public')); app.use(upload); app.post('/api/csvUpload',function(req,res) { upload(req,res,function(err) { // console.log(req.body); // console.log(req.files); if(err) { return res.end("Error uploading file"); } else{ res.send("File is uploaded"); } }); }); var server = app.listen(8081, function () { var host = server.address().address; var port = server.address().port; console.log("working on port 8081!"); }); 
 <!DOCTYPE html> <html> <head> <title>Home Page</title> </head> <body> <form id="uploadForm" action="/api/csvUpload" method="post" enctype="multipart/form-data"> <input type="file" name="csvFile"> <input type="submit" value="Upload File" /> </form> </body> </html> 

CSV to JSON CSV到JSON

 //This will process and convert a CSV file in to a JSON objec function csvJson(csv) { var lines = csv.split("\\n"); var result = []; 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 JSON.stringify(result); }; //Below is for testing purposes var testCSV = "userName, firstName, lastName, studentID, course\\n" + "username1,first1,last1,123456,Software Engineering\\n" + "username2,first2,last2,234567,Software Engineering\\n" + "username3,first3,last3,345678,Software Engineering\\n" + "username4,first4,last4,456789,Software Engineering"; var processedCSV = csvJson(testCSV); console.log(processedCSV); 

Because it's not completely clear for me how the files are uploaded, I'll start with the functions that gives the ability to load a (CSV)-file. 因为我不完全清楚文件是如何上传的,所以我将从能够加载(CSV)文件的函数开始。

For loading a file or url you can use XMLHttpRequest, more on this can be found at W3Schools . 对于加载文件或URL,您可以使用XMLHttpRequest,可以在W3Schools上找到更多相关信息。 This is a really powerful object, and I would really advice to read more into this. 这是一个非常强大的对象,我真的建议更多地阅读这个。

 /**
 * Loads file using XMLHttpRequest
 * @param {String} path
 * @param {Function} success
 * @param {Function} error
 */
function loadFile(path, success, error) {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                if (success)
                    success(csvToJSON(xhr.responseText));
            } else {
                if (error)
                    error(xhr);
            }
        }
    };
    xhr.open("GET", path, true);
    xhr.send();
}

To use this function, simply execute the following code: 要使用此功能,只需执行以下代码:

loadFile('Link_to_CSV_file.csv', function (data) {
        myFunction(data);
    }, function (xhr) {
        console.error(xhr);
    });

As soon the data is succesfully loaded, myFunction() will be executed with the data from loadFile() . 一旦数据成功加载, myFunction()将使用来自loadFile()的数据执行。 This can be used in the function. 这可以在函数中使用。

Finally, load the CSV-data in a function: 最后,在函数中加载CSV数据:

function myFunction(data){
    console.log(data);
}

PS: I would advice to convert the CSV file to JSON if you want to handle it in a javascript-function, if you're using Node.js, check out How to convert CSV to JSON in Node.js . PS:如果您想在javascript函数中处理它,我建议将CSV文件转换为JSON,如果您使用的是Node.js,请查看如何在Node.js中将CSV转换为JSON

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM