JQuery Form Plugin File Upload using POST redirects to POST response

后端 未结 5 1699
轮回少年
轮回少年 2021-01-19 01:34

Please help guys, This one is a major BLOCKER!

I have a project that uses NodeJS + jQuery Form Plugin + Typescript in which I am trying to do a file

5条回答
  •  轮回少年
    2021-01-19 02:41

    I think there are several different issues with your client-side code.

    I see that you define $form but I never see where you define form. You then call form.attr(...). Unless you have defined form somewhere else this will immediately throw an error.

    More importantly, standard $.ajax() cannot upload files on older browsers (even as recent as IE 9!) The ability to do an XHR file upload was added in XHR2 (see CanIUse). If you intend for your web app to have compatibility with any down-level browsers you'll need to work around this limitation in some way.

    The good news is that there are a variety of plugins that do most of the work for you. If you are using a version of jQuery greater than 1.6 I would recommend looking at the jQuery File Upload Plugin. It uses the new XHR file upload functionality when available and falls back on iFrame Transport in browsers that don't support the new hotness. While the iFrame Transport is simple and clever you don't really need to know anything about it, because the plugin abstracts it away. The plugin is completely free too.

    The Basic Plugin will do the dirty work for you and the full featured version even has a built in UI. There's plenty of details on how to implement the server side methods as well. The basic syntax is super simple:

    $("#fileUploadForm").fileupload()
    

    If you're looking for something even lighter weight, the iFrame Transport Plugin may be all you need. (It's free as well.) I just implemented it in a project today. It's a single very well documented JS file. It enhances the standard functionality of the $.ajax() function. The key is specifying iframe: true in your list of AJAX options. Your ajax call would probably look something like this:

    $.ajax("http://localhost", {
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        dataType: "JSON",
        iframe: true,
        files: $("#MyFileInputId"),
        success: function (data) {
            alert("Success : " + data);
        },
        error: function (data) {
            alert("Error : " + data);
        }
    });
    

    On a side note, if you want to make extra sure the non-AJAX POST doesn't occur, you can add another line to your code:

    $form.submit(function (e) {
        e.preventDefault();
        // do stuff
        return false;
    }
    

    preventDefault() will cancel the POST, even if an error occurs in the code that follows.

提交回复
热议问题