使用POST的JQuery表单插件文件上传重定向到POST响应 [英] JQuery Form Plugin File Upload using POST redirects to POST response

查看:126
本文介绍了使用POST的JQuery表单插件文件上传重定向到POST响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请帮助大家,这是一个主要的BLOCKER!

我有一个使用NodeJS + jQuery Form插件 + Typescript的项目,进行文件上传.上传文件后,服​​务器将发送响应到POST消息,该消息将显示在屏幕上.在屏幕上显示POST响应之前,文件确实已成功且完全上传.我希望POST响应调用成功"函数,而不是将页面重定向到显示JSON响应.

I have a project that uses NodeJS + jQuery Form Plugin + Typescript in which I am trying to do a file upload. After the file upload the server sends a response to the POST message which renders on the screen. The file does get uploaded successfully and completely before the POST response renders on the screen. I expect the POST response to call the "success" function instead of having the page redirected to show the JSON response.

代码如下:

$(new ID().setAsRoot().selectId()).append(
    "<form id=\"fileUploadForm\" accept-charset=\"utf-8\" method=\"post\" action=\"/upload\" enctype=\"multipart/form-data\">" +
        "<input id = \"filename\" type=\"file\" name=\"userfile\" multiple=\"multiple\" />" +
        "<button type=\"submit\" id = \"submitButton\"> Upload </button></form>");

var form = $("#fileUploadForm");
form.submit(function (e) {
    //e.preventDefault();
    this.ajaxSubmit({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize(),
        success: function (data) {
            var x = JSON.parse(data);
            alert("Success : " + x);
        },
        error: function (data) {
            var x = JSON.parse(data);
            alert("Error : " + x);
        }
    });
});

成功函数不会被调用(这意味着警报消息不会显示). JSON数据仅在屏幕上呈现,如下所示:

the success function does not get called (which means the alert message doesn't show). The JSON data just gets rendered on the screen like this:

{
  "path": "data\\cb3409f1cc234ec3f64b60d80be13a3e.html",
  "name": "feed.html"
}

控制台上显示错误消息:

There is an error on the console that says:

Uncaught SyntaxError: Unexpected token : shortcut_manager.js:123
(anonymous function) shortcut_manager.js:123
(anonymous function) extensions::messaging:327
Event.dispatchToListener extensions::event_bindings:386
Event.dispatch_ extensions::event_bindings:371
Event.dispatch extensions::event_bindings:392
dispatchOnMessage

这是处理它的服务器端代码.服务器使用NodeJS强大的模块.

Here's the server side code that handles it. The server uses NodeJS formidable module.

public upload(req:express.Request, res) {

        var form = new formidable.IncomingForm();
        var originalFileName:String;
        var filePath:String;
        form.uploadDir = this.directory;
        form.keepExtensions = true;
        form.type = 'multipart';
        var fields = [];
        form
            .on("error", function (err) {
            })
            .on("field", function (field, value) {
            })
            .on("end", function () {
                res.send({
                    path: filePath,
                    name: originalFileName
                });
            })
            .on("file", function (name, file:formidable.File) {
                originalFileName = file.name;
                filePath = file.path;
            });
        form.parse(req);
        return;
    }

-更新-

如果我使用$.ajax而不是this.ajax.该文件未上传.浏览器控制台显示错误:

If I do $.ajax instead of this.ajax. The file does not upload. The browser console shows an error:

XMLHttpRequest cannot load http://localhost/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. 

推荐答案

根据您的评论:

感谢您的建议.$ .ajax根本不会加载.它显示了您可能知道的错误.尽管您的怀疑是正确的,因为当我使用"this.ajax"时,文件确实被上传了,但是控制台显示错误类型没有方法ajax"

"Thanks for that suggestion. $.ajax does not load the at all. It shows an error which you may know of. Although your suspicion is right because, when I use "this.ajax" the file does get uploaded but the console shows an error "Type has no method ajax"

  • 您不能使用$.ajax()来上传文件,就像通常上传表单数据一样.
  • 由于使用this.ajax时出现错误,因此提交了表单.这就是为什么您在浏览器中看到JSON响应的原因.
  • You can't upload files using $.ajax() the same way you usually upload your form data.
  • Because of the error when you use this.ajax the form gets submitted. That's why you see the JSON response in the browser.

问题是this.ajax来自何处?您是否从使用未包含的库的示例复制了代码?

The question is where does this.ajax come from? Did you copy the code from an example that uses a library you haven't included?

要通过AJAX上传文件,您需要某种插件(自己动手会很费力,尤其是在需要支持旧版浏览器的情况下).

In order to upload files via AJAX you need some kind of plugin (doing it yourself is some effort, especially if you need support for older browsers).

提交处理程序应如下:

form.submit(function (e) {
  e.preventDefault();
  $(this).ajaxSubmit().done(function (data) {
    var x = JSON.parse(data);
    alert("Success : " + x);
  }).fail(function (data) {
    var x = JSON.parse(data);
    alert("Error : " + x);
  });
});

说明:由于要调用jQuery插件,因此需要jQuery对象,因此为$(this). ajaxSubmit()不需要任何参数(不过,您可以根据需要传递选项).因为我没有传递参数,所以在donefail(而不是successerror)中附加了回调.

Explanation: Since you want to call a jQuery plugin you need a jQuery object, hence $(this). ajaxSubmit() does not need any arguments (you can pass in options if you want, though). Because I didn't pass in arguments the callbacks are appended, in this case with doneand fail (instead of success and error).

这篇关于使用POST的JQuery表单插件文件上传重定向到POST响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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