主要来自未发送文件的nodejs dropzone

时间:2019-08-07 08:34:21

标签: javascript node.js file-upload multer dropzone

我正在尝试让Dropzone在带有其他字段的房屋创建表单中工作,但是我无法以任何方式使其发送文件。

我有这个表格:

<form id="dropzone" class="dropzone">

    <div class="flex">

        <div class="fieldset-wrapper">

            <fieldset>

                <div class="input-wrapper">
                    <input type="text" name="address" placeholder="Adresse" class="">
                </div>

                <div class="input-wrapper">
                    <input type="number" name="zipcode" placeholder="Postnr" class="">
                </div>
                <div class="input-wrapper">
                    <input type="text" name="city" placeholder="By" class="">
                </div>
            </fieldset>

            <fieldset>
                <legend>Contact info</legend>

                <div class="input-wrapper">
                    <input type="tel" name="phone1" placeholder="Phone 1" value="" class="">
                </div>

                <div class="input-wrapper">
                    <input type="tel" name="phone2" placeholder="Phone 2" value="" class="">
                </div>

                <div class="input-wrapper">
                    <input type="email" name="email1" placeholder="E-mail 1" class="">
                </div>

                <div class="input-wrapper">
                    <input type="email" name="email2" placeholder="E-mail 2" class="">
                </div>

            </fieldset>

        </div>

    </div>

    <div class="dropzone dz-clickable" id="myDrop">
        <div class="dz-default dz-message" data-dz-message="">
            <span>Upload or drag patient photo here</span>

            <div class="fallback">
                <input name="photo" type="file" />
            </div>
        </div>
    </div>

    <input type="hidden" name="uid" value="<%= uid %>" />
    <button type="submit" id="newHouseButton" class="button">Create house</button>

</form>

这个JavaScript:

<script>

Dropzone.autoDiscover = false

document.addEventListener('DOMContentLoaded', () => {

    let form = document.getElementById('dropzone')
    let button = document.getElementById('newHouseButton')
    let errorBox = document.getElementById('error')
    let confirmBox = document.getElementById('confirm')

    let myDropzone = new Dropzone("#dropzone", {
        url: "/upload",
        method: 'post',
        addRemoveLinks: true,
        autoProcessQueue: false,
        acceptedFiles: 'image/*',
        maxFilesize: 1,
        maxFiles: 5,
        parallelUploads: 100,
        uploadMultiple: true,
        paramName: 'photo',
        init: function () {

            var myDropzone = this;

            button.addEventListener('click', (e) => {
                e.preventDefault()
                e.stopPropagation();

                const formData = new FormData()
                formData.append('userid', form.querySelector('input[name="uid"]').value)
                formData.append('streetaddress', form.querySelector('input[name="address"]').value)
                formData.append('zipcode', form.querySelector('input[name="zipcode"]').value)
                formData.append('city', form.querySelector('input[name="city"]').value)

                let services = form.querySelectorAll('input[name="services"]:checked')
                let serviceArray = []

                services.forEach((item) => {
                    serviceArray.push(item.value)
                })

                formData.append('services', serviceArray)

                myDropzone.processQueue();

                // const config = {
                //     headers: {
                //         'content-type': 'multipart/form-data'
                //     }
                // }


                // axios.post('/profile/house/create', formData, config).then((response) => {

                //     if (response.data.success === false) {
                //         errorBox.textContent = response.data.message
                //     } else {
                //         confirmBox.textContent = response.data.message
                //     }

                // }).catch((error) => {
                //     console.log(error)
                //     errorBox.textContent = error.response.data.message
                // })

            })

            this.on("sendingmultiple", function () {
                console.log('sending')
            });

            this.on('success', function (file, resp) {
                console.log(file);
                console.log(resp);
            });

            this.on("successmultiple", function (files, response) {
                console.log(files)
            });

            this.on("errormultiple", function (files, response) {
                console.log(response)
            });


        }
    })

})
</script>

在服务器上,我尝试像这样处理它:

server.js

const upload = require('./app/middleware/upload')

app.post('/upload', upload.array('photo', 5), (req, res) => {
    console.log(req.files)
})

upload.js

const multer = require('multer');

const multerConfig = {
    storage: multer.diskStorage({

      destination: function(req, file, next){
        next(null, './public/upload/images');
      },

      filename: function(req, file, next){
        const ext = file.mimetype.split('/')[1];
        next(null, Date.now() + '.' + ext)
      }
    }),

    fileFilter: function(req, file, next) {

    if(!file){
        next();
      }

      const image = file.mimetype.startsWith('image/');

      if (image) {
        next(file, true);
      } else {
        return next();
      }

    }
  }

  module.exports = multer(multerConfig)

但是它根本不发送文件,而且我也无法进入upload.js(console.log()的任何地方都不起作用。

console.log(req.files)

只返回[]

在前端,它在图片下方显示“取消上传”并提交点击,因此似乎没有发送图片。我只是不知道我在做什么错。

基本上,我想使用单一表单发送图像(如果有的话-它是可选的),如果一切顺利,我想将表单发布到创建内部POST端点,以将表单数据插入数据库-也使用文件名。

0 个答案:

没有答案