使用jQuery,Express.js和AJAX

时间:2018-04-15 14:52:18

标签: jquery ajax express multer

我尝试使用multer npm模块上传文件,使用Express.js,jQuery和AJAX。根据Postman的说法,我的API在上传文件时工作正常。我的问题出在jQuery方面。

后端

var express = require('express');
var path = require('path');
var router = express.Router();
var Post = require('../models/posts');
var checkPost = require('../middleware/check-post');
var multer = require('multer');         //Module to upload files to the database

/**
 * Specification variable to place the file in the './uploads/' directory and what to call them
 */
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads/posts');
  },
  filename: function (req, file, cb) {
    cb(null, new Date().toISOString() + file.originalname)      //new Date().toISOString() converts the current date to a string
  }
});

/**
 * Specification variable to filter for the file types that can be uploaded to posts
 */
const fileFilter = function (req, file, cb) {
  var fileTypes = ['image/jpeg', 'image/png', 'application/pdf', 'application/msword',                           //File types that are allowed
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',                                      //.jpeg, .png, .pdf, .doc, .docx, .ppt, .pptx
    'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation']

  if (fileTypes.indexOf(file.mimetype) > -1) {     //Checks to see if file.mimetype is in the fileFilter array
    cb(null, true);
  } else {
    cb(null, false);
  }
};

/**
 * Adds the specification variables to 'multer' and saves them in the upload variable
 */
var upload = multer({
  storage: storage,
  limits: {
    fileSize: 1024 * 1024 * 10       //Sets the file size limit to 10MB
  },
  fileFilter: fileFilter
});

/**
 * Adds posts to our database
 */
router.post('/addPost', upload.single('post_file'), function (req, res, next) {
  var post = new Post(req.body);

  if (req.file) {
    post.post_file = req.file.path
  }

  post.save(function (err, savedPost) {
    if (err)
      res.status(500).json(err);

    res.status(201).json({
      status: "Successfully added the post",
      id: savedPost._id
    });
  });
});

前端(HTML)

<div class="container-fluid">
  <div class="col-xs-offset-2">
    <h1>Create a Post</h1>
  </div>
</div>

<div class="container-fluid">
  <div class="well col-xs-10 col-xs-offset-1">
    <div class="row col-xs-10 col-xs-offset-1">
      <form class="form-horizontal" role="form" id="postForm">
        <div class="row">
          <div class="form-group">
            <div class="col-xs-12">
              <textarea class="form-control required" style="min-width: 100%" rows="1" placeholder="Title" id="inputPostTitle"></textarea>
            </div>
          </div>
        </div>
        <!---Title--->

        <div class="row">
          <div class="form-group">
            <div class="col-xs-12">
              <textarea class="form-control required" style="min-width: 100%" rows="5" placeholder="Desciption" id="inputPostDesc"></textarea>
            </div>
          </div>
        </div>
        <!---Description--->

        <div class="row">
          <div class="form-group">
            <div class="col-xs-3">
              <label class="btn btn-info">
                <span class="glyphicon glyphicon-paperclip">
                  <input type="file" id="inputPostFile" hidden>
                </span> Attach Files
              </label>
            </div>
            <div class="col-xs-7">
            </div>
            <div class="col-xs-2">
              <a href="#" data-toggle="popover" data-placement="bottom" data-content="Please enter your post...">
                <button type="text" class="btn btn-warning btn-lg">Post</button>
              </a>
            </div>
          </div>
        </div>
        <!---Buttons--->

      </form>
    </div>
  </div>
</div>

<script src="/javascripts/create-post.js"></script>

前端(jQuery)

$(document).ready(function () {
  /**
   * Event handler for when the user submits a post
   */
  $("#postForm").submit(function (event) {
    event.preventDefault();

    var path = window.location.pathname;
    var fields = path.split("/");
    var module = fields[4];                           //Module code
    var route = path.replace("/createPost", "");      //Route for the POST request
    var file = document.getElementById("inputPostFile").files[0];
    var formData = new FormData();
    formData.append("inputPostFile", file);
    console.log(formData);

    $.ajax({
      url: route + '/addPost',
      type: 'POST',
      data: formData,
      contentType: false,
      processData: false,
      successs: function() {
        console.log('success');
      },
      error: function() {
        console.log('error');
      }
    })
  });
});

控制台返回POST 500内部错误。我该如何修改?我可以在文件中附加更多表单数据吗?

1 个答案:

答案 0 :(得分:1)

在您的ajax中,您将文件指定为inputPostFile,但在服务器端指定为post_file
将其更改为ajax中的post_file

formData.append("post_file", file);

您可以使用相同的追加功能添加任何数据 此外,您可以将表单作为参数传递给FormData构造函数,以添加表单中的所有字段,这样您就不必使用append。
如果您这样做,则必须在表单字段中添加名称属性。