将CSV文件从浏览器发送到Node.js服务器 [英] Sending a CSV file from browser to nodejs server

查看:66
本文介绍了将CSV文件从浏览器发送到Node.js服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将用户上传的csv文件从浏览器发送到nodejs服务器进行处理(文件超过50 mb,因此页面无响应).我为此使用XMLHttpRequest.我找不到解决方案.感谢您的帮助.

I am trying to send a csv file which is uploaded by the user, from browser to nodejs server for processing (file is over 50 mb, so the page becomes unresponsive). I'm using XMLHttpRequest for this purpose. I cannot find a solution to this. Any help is appreciated.

 var csv = document.getElementById('inputFile').files[0];
 var request = new XMLHttpRequest();
 request.open("POST", "/handleFile", true);
 request.setRequestHeader("Content-type", "text/csv");
 request.onreadystatechange = function() {
   if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {
     console.log("yey");
   }
 }

 request.send(csv);

NodeJS服务器

 var express = require('express')
 var app = express()
 var bodyparser = require('body-parser')

 app.post('/handleFile', function(req, res) {
   console.log(req.body); // getting {} empty object here....
   console.log(req);

   var csv = req.body;
   var lines = csv.split("\n");
   var result = [];
   var headers = lines[0].split("\t");

   for (var i = 1; i < lines.length; i++) {
     var obj = {};
     var currentline = lines[i].split("\t");

     for (var j = 0; j < headers.length; j++) {
       obj[headers[j]] = currentline[j];
     }

     result.push(obj);
   }

   fileData = result;
 });

我做错了什么?XMLHttpRequest使用不正确吗?还是我不理解的其他事情?为什么req.body中没有数据,即使它是发布请求也是如此.还是有其他方法可以从前端将csv/文本文件发送到nodejs服务器.

What did I do wrong? Is the XMLHttpRequest used incorrectly? or there is some other thing that i did not understand ? why is there no data in req.body even though its a post request. Or is there any other way to send a csv/text file to nodejs server from front end.

这个问题不是重复的,因为正文解析器(即负责解析req.body的中间件)无法处理text/csv和multipart/form-data.上面的链接不是正确的解决方案.

This question is not a duplicate because, the body-parser i.e. the middleware responsible for parsing the req.body does not handle text/csv and multipart/form-data . The above link is not the correct solution.

推荐答案

因此,环顾四周后,我发现问题不是我的XMLHttpRequest.服务器很好地接收了该请求,但是主体解析器无法解析text/csv和multipart/form-data内容类型.这是逐步解决此问题的方法.

So, after looking around, I found that the problem was not my XMLHttpRequest. The request was received by the server just fine, but the body-parser could not parse the text/csv and multipart/form-data content-type. Here is the step by step answer to this problem.

  1. 每当您向服务器发送大文件时,在客户端/浏览器端,请将其转换为multipart/form-data.这是将text/csv/anyfile发送到服务器的正确方法.

  1. In the client/browser-end whenever you are sending a large file to the server, convert it into multipart/form-data . It is the correct way of sending a text/csv/anyfile to the server.

var csv=document.getElementById('inputFile').files[0];
var formData=new FormData();
formData.append("uploadCsv",csv);
var request = new XMLHttpRequest();

 //here you can set the request header to set the content type, this can be avoided.
 //The browser sets the setRequestHeader and other headers by default based on the formData that is being passed in the request.
 request.setRequestHeader("Content-type", "multipart/form-data"); //----(*)
 request.open("POST","/handleFile", true);
request.onreadystatechange = function (){
    if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
    console.log("yey");
    }
}

request.send(formData);

因此,这就是将http请求发送到nodejs服务器的方式.

So, this is how you'll send your http request to the nodejs server.

  1. 在Node js服务器上:通常对于application/json或任何其他请求类型,body解析器都可以正常工作.但是对于大数据和文件,即multipart/form-data body-parser无法解析req.body.因此它将给req.body作为{}(空对象).在此处了解有关的信息.

因此对于这些内容类型,您可以使用其他中间件来处理请求.一些是 multer ,多方聚会,花花公子等.我使用了multer.这是代码片段.

So for these content-type you can use other middleware for handleling the request. Some are multer,multiparty,busboy etc. I used multer. Here is the code snipet.

    //EXPRESS
    var express = require('express')
    var app = express()

    var config=require('./config.js');
    //multer
    var multer  = require('multer');
    var upload = multer();
    app.post('/handleFile',upload.single('uploadCsv'), function(req, res, next) {
          // req.file is the `uploadCsv` file 
          // req.body will hold the text fields, if there were any 
          console.log(req.file);
          // the buffer here containes your file data in a byte array 
          var csv=req.file.buffer.toString('utf8');
     });

注意:这仍然会在nodejs服务器中给您一个错误.提示:与(*)行有关.尝试将其删除,然后看看会发生什么.谷歌其余的;)

NOTE: This will still give you an error in nodejs server. hint: It has something to do with the line (*). Try removing it and see what happens. Google the rest ;)

这篇关于将CSV文件从浏览器发送到Node.js服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆