【问题标题】:How to upload file with nodejs如何使用nodejs上传文件
【发布时间】:2013-12-09 19:33:01
【问题描述】:

我想用 nodejs 上传一张图片。

我将文件发送到节点,但接下来的问题是我不知道如何处理“req”。

客户

<html>
    <body>
        <input id="uploadInput" type="file"/>
        <div id="uploadShow"></div>

        <script type="text/javascript">
            uploadInput = document.getElementById("uploadInput");
            uploadInput.onchange = function() {  //when file ready to upload
                if(uploadInput.files && uploadInput.files[0]) {
                    var file = uploadInput.files[0];  //I want to send the file
                    var xhr = new XMLHttpRequest();

                    if (xhr.readyState == 4 && xhr.status == 200) {
                        var uploadShow = document.getElementById("uploadInput");
                        uploadShow.innerHTML = xhr.responseText;  //show file
                    }

                    xhr.open('POST', "/upload", false);
                    xhr.send(file);  //send file...
                }
            };
        </script>
    </body>
</html>

服务器

var http = require('http'),url = require("url"),
    path = require('path'),fs = require('fs');

http.createServer(function(req, res) {
    var filename = "/index.html";
    if (req.url !== "/") {
       filename = url.parse(req.url, true).pathname;
       filename = filename.split("?")[0];
    }
    if (filename === "/upload" && req.method.toLowerCase() == 'post') {
        //deal the request of ajax

        **upload_file**(req, res);  //can you help me to write this function

        return;
    }
    //the following fs.readFile index.html

}).listen("192.168.39.9", 8888);

如何上传图片和节目?

【问题讨论】:

  • files[0] 可能并没有真正给你文件,更像是一个具有高度、宽度和 url 'fakepath/image.png' 或其他东西的对象,而这只是一个字符串。图像将位于 formData 对象中。

标签: javascript html ajax node.js


【解决方案1】:

我认为文件上传不会那样工作。如果你用express没问题,我建议你使用强大的支持ajax文件上传;

在这里查看:https://stackoverflow.com/a/20372845/1520518

【讨论】:

    猜你喜欢
    • 2014-03-16
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多