通过Ajax Node.js Express上传带有表单的文件 [英] upload file with a form via ajax nodejs express

查看:243
本文介绍了通过Ajax Node.js Express上传带有表单的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是ajax文件

$(form).submit(function()
            {
                $.ajax(
                {
                    url:'/newProduct',
                    cache: false,
                    type: 'POST',
                    data: $(form).serialize(),
                    success:function(datos)
                    {
                        console.dir(datos)
                    },
                    error:function(xhr,tm)
                    {

                    },
                    complete:function()
                    {
                        form.reset();

                    }
                })
return false        

            });

此在服务器上

exports.newProduct=function(req,res)
{
    console.dir(req.body)
    console.dir(req.files)
    return res.send('Producto Cargado correctamente.');
}

文件未上传,服务器上的信息未显示,没有任何反应

the file didnt upload, the info on server shows nothing, nothing happends

推荐答案

(据我所知)您不能使用$.ajax来执行 multipart/form-data 表单提交(并非没有手动构建POST主体). Express文件上载要求您的HTML <form>元素设置为enctype="multipart/form-data"属性.你有设置吗?

You can't (as far as I understand it) use $.ajax to perform a multipart/form-data form submission (not without manually building the POST body). The Express file upload requires that your HTML <form> element have the enctype="multipart/form-data" attribute set. Do you have it set?

对于您要执行的操作,您可能想要使用隐藏的iframe来执行发布,然后让服务器返回一个JavaScript代码段,该代码段会成功/失败地进行回调.有许多jQuery插件可以为您做到这一点(我相信 jQuery Form 可以做到) ).

For what you're trying to do you probably want to use a hidden iframe to perform the post, then have the server return a javascript snippet that calls back with success/failure. There are a number of jQuery plugins that do this for you (jQuery Form does it, I believe).

这篇关于通过Ajax Node.js Express上传带有表单的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆