如何使用Node JS上传文件? [英] How do I upload a file using node js?

查看:88
本文介绍了如何使用Node JS上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我环顾四周,并查看了有关如何使用node/express上传文件的各种教程.我觉得我在HTML或JQuery方面都做错了. 我使用以下链接作为 http://howtonode.org/really-simple-file-uploads .

I have looked around and looked at various tutorials on how to upload a file using node/express. I feel like I am doing something wrong on either the HTML or JQuery side. I am using the following link as a http://howtonode.org/really-simple-file-uploads.

但是我遇到了错误:

TypeError: Cannot read property 'fileUpload' of undefined    at module.exports.fileCreate 

这是我的下面的代码:

uploadcontroller.js

uploadcontroller.js

fs.readFile(req.files.fileUpload.path, function (err, data) {
    var newPath = __dirname + "/uploads/" + imgString;
    fs.writeFile(newPath, data, function (err) {
    });
});

html代码段

<div class="form-group">
    <label for="fileUpload">Upload File</label>
    <input type="file" name="fileUpload" id="fileUpload">
</div>

我正在使用Sails框架(不确定是否会有所不同)

I am using the Sails framework (not sure if that makes difference)

完整表格

<form role="form" class="uploadFileForm">
    <div class="form-group">
        <label for="fileTitleInput">Title</label>
        <input type="text" name="formTitleInput" id="formTitleInput">
    </div>
    <div class="form-group">
        <label for="fileDescriptionInput">Description</label>
        <textarea class="form-control" rows="4" id="fileDescriptionInput"></textarea>
    </div>
<div class="form-group">
        <label for="fileUpload">Upload File</label>
        <input type="file" name="fileUpload" id="fileUpload">
    </div>
    <button type="submit" class="btn btn-default" id="file-submit-btn">Publish to Web</button>
</form>

推荐答案

app.post('/upload', function(req, res) {

    fs.readFile(req.files.image.path, function (err, data) {

        var imageName = req.files.image.name

        /// If there's an error
        if(!imageName){

            console.log("There was an error")
            res.redirect("/");
            res.end();

        } else {

          var newPath = __dirname + "/uploads/fullsize/" + imageName;

          /// write file to uploads/fullsize folder
          fs.writeFile(newPath, data, function (err) {

            /// let's see it
            res.redirect("/uploads/fullsize/" + imageName);

          });
        }
    });
});

这篇关于如何使用Node JS上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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