NodeJS从本地计算机上传文件到远程服务器

时间:2017-11-29 17:23:34

标签: jquery node.js ajax

所以我在本地机器上工作,我能够将文件从路径A上传到B。

以下代码

HTML

<form action="/fileupload" method="post" enctype="multipart/form-data">
   <input type="hidden" class="form-control" name="csrfmiddlewaretoken" value="{{_csrf}}">
   <input type="file" name="filetoupload"><br>
   <input type="submit">
 </form>

的NodeJS

app.post('/fileupload', function (req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      var oldpath = files.filetoupload.path;
      var newpath = 'C:/Users/MyName/uploadtesterFile/' + files.filetoupload.name;


      fs.rename(oldpath, newpath, function (err) {
        console.log(err);

        if (err) throw err;
        res.redirect(req.get('referer'));
      });
    });
 })

将文件上传到C:/ Users / MyName / uploadtesterFile / successfully 但当我将其更改为远程服务器路径时,它会返回错误,不允许跨设备链接以及某些内容......等等。

enter image description here

有没有参考?我正在学习W3Cschool教程。

1 个答案:

答案 0 :(得分:1)

有一个名为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
})

app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
  // req.files is array of `photos` files
  // req.body will contain the text fields, if there were any
})

var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
  // req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
  //
  // e.g.
  //  req.files['avatar'][0] -> File
  //  req.files['gallery'] -> Array
  //
  // req.body will contain the text fields, if there were any
})