提问者:小点点

node.js:用ajax将上传的文件从html发送到节点js


目的:上传一个html格式的文本文件,并在节点服务器中访问其数据。

我认为可行的办法是:

方法1:使用客户端JavaScript读取文件中的文本,并使用ajax将读取的数据发送到节点

方式2:将整个上传文件发送到节点服务器,并在后端读取


共1个答案

匿名用户

我做了一些搜索,但没有一个是中肯的,所以这里是我的解决方案,可以与任何程序很容易地集成。

模块安装

npm install express-fileupload express ejs

用于解析客户端发送的文件数据

app.js安装程序

const fileupload = require('express-fileupload')
const express = require("express")

const app = express()
app.use(fileupload())
app.set("view-engine","ejs")


app.post('/yourPath',(req,res)=>{
    var buffertoData = (req.files.CSVfiles.data).toString('utf8') 
    //The data received is in buffer so convert them to string
    console.log("Files>"+buffertoData)
})

app.listen(3000,()=>{console.log("Started server in 3000...")})

客户端。ejs

<html>
    <!-- Here I have used jquery to use div as input button as I already made an UI but you can use a button and skip jquery -->
    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
...
    <div id="clicktodrop" class="clicktodrop">Or Click Here</div>
    <input onchange="onChooseFile(event))" type="file" name="fileToUpload" id="fileToUpload"style="display:none;"/>
...

<script>
    //Part to make div to act as input by triggering the hidden input to take file input
    //You can skip this if you use the input directly
    $('#clicktodrop').click(function(){ 
        $('#fileToUpload').trigger('click'); 
    });

    function sendFiletoNode(file){
        var formData = new FormData(),file, reader;
        formData.append('CSVfiles', file.target.files[0]);
        $.ajax({
                url : '/yourPath',
                type : 'POST',
                data : formData,     // The data is sent through ajax so no need to refresh page
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                success : function(data) {}
        });
    }

    function onChooseFile(event) {
        if (typeof window.FileReader !== 'function')
            throw ("The file API isn't supported on this browser.");
        let input = event.target;
        if (!input)
            throw ("The browser does not properly implement the event object");
        if (!input.files)
            throw ("This browser does not support the `files` property of the file input.");
        if (!input.files[0])
            return undefined;
        let file = input.files[0];
        let fr = new FileReader();
        sendFiletoNode(event)
        fr.readAsText(file);
    }
</script>
</html>

这整个代码不是我自己写的,而是我使用了不同的答案,从SO,并使它适合我的需要。

如果代码有问题,请注释并告诉我。另外,我也是node js的新手。我想我会把我的代码分享给那些正在寻找小而紧凑的代码以满足他们的需要而不是膨胀软件代码的人。

相关问题