javascript - 如何在node js中将文件上传到服务器上?

标签 javascript jquery node.js multer

您能告诉我如何在当前示例的某个目录(uploads 文件夹)上上传文件吗?这是我的服务器端代码

app.post('/upload', function (req, res) {
  console.log('abcc')
    upload(req, res, function (err) {
        if (err) {
            res.json({error_code: 1, err_desc: err});
            return;
        }
        res.json({error_code: 0, err_desc: null});
    });
});

完整代码 Node js https://repl.it/repls/LustrousCharmingCommunication

我使用此服务器并使用客户端访问该服务并仅上传附件

这是我的请求客户端代码 https://jsbin.com/luwezirive/edit?html,js,output

 $(function () {
        $('.submit').on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            if ($('#fileId').val().length === 0) {
                alert('please insert file')
            } else {
                var form = $('#fileUploadForm')[0];

                // Create an FormData object
                var data = new FormData(form);
              console.log('fffff')
                $.ajax({
                    url: 'https://lustrouscharmingcommunication--five-nine.repl.co/upload',
                    type: 'POST',
                    data: data,
                    cache: false,
                    enctype: 'multipart/form-data',
                    dataType: 'json',
                    processData: false, // Don't process the files
                    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
                    success: function (data, textStatus, jqXHR) {
                      console.log('succsss'); 
                      if (typeof data.error === 'undefined') {
                            // Success so call function to process the form
                        }
                        else {
                            // Handle errors here
                            console.log('ERRORS: ' + data.error);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        // Handle errors here
                        console.log('ERRORS: ' + textStatus);
                        // STOP LOADING SPINNER
                    }
                });
            }
        })
    })

我成功了,但文件没有上传,为什么?

上传方式

var storage = multer.diskStorage({ //multers disk storage settings
    destination: function (req, file, cb) {
        cb(null, './uploads/')
    },
    filename: function (req, file, cb) {
        var datetimestamp = Date.now();
        cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1])
    }
});
var upload = multer({ //multer settings
    storage: storage
}).single('file');

有更新吗?

最佳答案

最简单的方法是使用multerhttps://github.com/expressjs/multer

取自文档的示例:

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' })

var app = express()

app.post('/profile', upload.single('avatar'), function (req, res, next) {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
})

关于javascript - 如何在node js中将文件上传到服务器上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51871989/

相关文章:

javascript - 循环遍历数组并使用 d3 将每个项目分配为 html 标签中的类

javascript - JS/React 函数返回字符串属性但返回 [object Object]

javascript - AngularJS JSON 格式

javascript - 基于屏幕的 jquery 中心元素,而不是页面大小

javascript - 使用 Node 和 Angular 从 Last.fm API 获取搜索结果

node.js - Firebase 函数找不到模块 'cycle'

javascript - React js getInitialState 转换为 es6 后不起作用

javascript - 如何注释返回状态片段的函数的流类型?

javascript - 使用 jQuery 在一组图像上定位文本

javascript - Gulp3 到 gulp 4 升级。带条件的函数