Show errors when uploading photo with dropzone

2019-07-09 08:31发布

Hi I have problem with upload image in jquery. When i uplaod image ,show me errors. How do i solve this peroblem ?

I can't use the form to dropzone because it is in another form. Errors:

POST http://localhost:3000/upload 400 (Bad Request)

Object {error: Object}

code html

<div class="dropzone" action="/upload"  encType="multipart/form-data" method='post' id="id_dropzone" >
<div class="dz-message">
  ِDrop file here to upload
</div>
 </div>

Code JQUERY

  $(document).ready(function(){

    Dropzone.autoDiscover = false;

$("#id_dropzone").dropzone({addRemoveLinks: true, autoQueue: true,paramName: "file", maxFilesize: 2, maxFiles: 1,

    success: function (file, response) {
            var imgName = response;
            file.previewElement.classList.add("dz-success");
            console.log("Successfully uploaded :" + imgName);
        },
        error: function (file, response) {
            file.previewElement.classList.add("dz-error");
              console.log(response);
        },
  maxThumbnailFilesize: 1,acceptedFiles: "image/*"  });
})

Code app.js

    var express = require('express');
    var routes = require('./routes')();
    var fileUpload = require('express-fileupload');
    var path = require('path');
    var app = express();

    app.use(fileUpload());
    app.use('/files', express.static(__dirname + '/files'));
    .
    .
    .
    app.post('/upload', function(req, res) {
      var sampleFile;
      if (!req.files) {
        res.send('No files were uploaded.');
        return;
      }
      sampleFile = req.files;
      console.log(sampleFile);
      sampleFile.file.mv(__dirname + '/files/'+sampleFile.file.name, 
      function(err) {
        if (err) {
          console.log(err);
          res.status(500).send(err);
        } else {
        res.send('File uploaded!');
      }
    });
  });

package.json

{
  "name": "application-name",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
    "connect-mongo": "~0.3.3",
    "ejs": "^2.5.6",
    "express": "^3.21.2",
    "express-fileupload": "^0.1.4",
    "mongoose": "~3.6.19"
  },
  "devDependencies": {
    "mocha": "~1.12.1",
    "should": "~1.2.2",
    "supertest": "~0.7.1"
  }
}

2条回答
神经病院院长
2楼-- · 2019-07-09 09:14

I solved this problem with the following code.

app.js

var multiparty = require('multiparty');
const fs = require('fs');
var util = require('util');
.
.
.
    app.post('/file-upload', function(req,res){
      var form = new multiparty.Form({autoFiles:true });
      form.parse(req, function(err, fields, files) {
        res.writeHead(200, {'content-type': 'text/plain'});
        res.write('received upload:\n\n');
        var oldpath = req.files.file.path;
        var newpath =  __dirname + '\\files\\' + req.files.file.name;
        var readStream = fs.createReadStream(oldpath);
        var writeStream = fs.createWriteStream(newpath);
        readStream.pipe(writeStream);
        res.end();
      });
      return;
   });
查看更多
干净又极端
3楼-- · 2019-07-09 09:20

I have made a working example based on your code, and I could not reproduce the error. File get successfully uploaded.

Only difference is that I have moved Dropzone.autoDiscover = false; line before document.ready block.

Here is a full working source based on your code

server.js

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

app.use(fileUpload());
app.use('/files', express.static(__dirname + '/files'));
app.use('/', express.static(__dirname + '/'));

app.post('/upload', function(req, res) {
  var sampleFile;
  if (!req.files) {
    res.send('No files were uploaded.');
    return;
  }
  sampleFile = req.files;
  console.log(sampleFile);
  sampleFile.file.mv(__dirname + '/files/' + sampleFile.file.name,
    function(err) {
      if (err) {
        console.log(err);
        res.status(500).send(err);
      } else {
        res.send('File uploaded!');
      }
    });
});


//init server
app.listen(3000, function() {
  console.log("Server running on port 3000");
});

index.html

<html>
<head>
  <script
      src="https://code.jquery.com/jquery-3.2.1.js"
      integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
      crossorigin="anonymous"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.1.1/dropzone.js"></script>
</head>
<body>
<div class="dropzone" action="/upload" encType="multipart/form-data" method='post' id="id_dropzone">
  <div class="dz-message">
    ِDrop file here to upload
  </div>
</div>
</body>
</html>
<script>
  Dropzone.autoDiscover = false;

  $(document).ready(function() {
    $("#id_dropzone").dropzone({
      addRemoveLinks: true, autoQueue: true, paramName: "file", maxFilesize: 2, maxFiles: 1,
      success: function(file, response) {
        var imgName = response;
        file.previewElement.classList.add("dz-success");
        console.log("Successfully uploaded :" + imgName);
      },
      error: function(file, response) {
        file.previewElement.classList.add("dz-error");
        console.log(response);
      },
      maxThumbnailFilesize: 1, acceptedFiles: "image/*"
    });
  })
</script> 

package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.15.3",
    "express-fileupload": "^0.1.4"
  }
}
查看更多
登录 后发表回答