在express中上传图像只是挂起

时间:2017-02-22 17:45:47

标签: javascript node.js express

html

  <form method='post' action='upload_bg' enctype="multipart/form-data">
  <input type='file' name='fileUploaded'>
  <input type='submit'>

我的index.js

app.route('/upload_bg')
    .post(function (req, res) {
        var fstream;
        req.busboy.on('file', function (fieldname, file, filename) {
          console.log(filename);
            fstream = fs.createWriteStream(__dirname + '/imgs/' + "latest_upload.jpg");
            file.pipe(fstream);
            fstream.on('close', function () {
                res.redirect('back');
            });
        });
    });

我的变数:

var express = require('express');
var busboy = require('connect-busboy');
var path = require('path');
var fs = require('fs-extra');

因此,用户单击按钮,选择图像,然后选择提交。这点击了我的路线upload_bg。我之前已经开始工作了,我改变了一些事情,但我无法理解为什么它不起作用。我查看网络选项卡,请求无限期地挂起。

2 个答案:

答案 0 :(得分:0)

我会亲自重新设计你的代码。我会使用ajax。以下是一些示例代码:

index html

<button class="btn btn-lg upload-btn" type="button">Upload image</button>
<input id="upload-input" type="file" name="uploads[]" multiple="multiple">

client js

这可以/应该在index.html

之内
$('.upload-btn').on('click', function (){
    $('#upload-input').click();
    $('.progress-bar').text('0%');
    $('.progress-bar').width('0%');
});

$('#upload-input').on('change', function(){

  var files = $(this).get(0).files;

  if (files.length > 0){
    // create a FormData object which will be sent as the data payload in the
    // AJAX request
    var formData = new FormData();

    // loop through all the selected files and add them to the formData object
    for (var i = 0; i < files.length; i++) {
      var file = files[i];

      // add the files to formData object for the data payload
      formData.append('uploads[]', file, file.name);
    }

    $.ajax({
      url: '/upload',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function(data){
          console.log('upload successful!\n' + data);
      },
    });

  }
});

server js

var express = require('express');
var app = express();
var path = require('path');
var formidable = require('formidable');
var fs = require('fs');
var l;

//... other code here


app.get('/upload', function(req, res){
  res.sendFile(path.join(__dirname, 'index.html'));
});

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

  var form = new formidable.IncomingForm();

  form.multiples = true;

  form.uploadDir = path.join(__dirname, '/uploads');

  form.on('file', function(field, file) {
    fs.readdir('uploads/', function(err, items) {
        console.log(items.length);
        l = items.length
        console.log(l);
        fs.rename(file.path, "uploads/"+l+".jpg", function(err) {
            if ( err ) console.log('ERROR: ' + err);
        });
    });
  });

  form.on('error', function(err) {
    console.log('An error has occured: \n' + err);
  });

  form.on('end', function() {
    res.end('success');
  });

  form.parse(req);

});

希望这有帮助!

答案 1 :(得分:0)

以下是使用express-fileupload模块的简单解决方案: 首先使用以下命令快速表达fileupload模块:

 npm install express-fileupload

HTML网页代码:

<html>
<body>
<form ref='uploadForm' 
  id='uploadForm' 
  action='http://localhost:3000/upload_bg' 
  method='post' 
  encType="multipart/form-data">
    <input type="file" name="sampleFile" />
    <input type='submit' value='Upload!' />
</form>     
</body>
</html>

节点服务器代码: server.js:

var express=require('express');

var app = express();

var fileUpload = require('express-fileupload');

// default options
app.use(fileUpload());

app.post('/upload_bg', function(req, res) {
  if (!req.files)
    return res.status(400).send('No files were uploaded.');

  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
  let sampleFile = req.files.sampleFile;

  // Use the mv() method to place the file somewhere on your server
  // Make sure 'imgs' folder is already created inside current directory otherwise it will throw error where this server.js file is placed
  sampleFile.mv(__dirname + '/imgs/latest_upload.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});

app.listen(3000,function(){
    console.log("App listening on port 3000")
});

希望这会有所帮助。有关完整代码,请参阅https://github.com/richardgirges/express-fileupload