The Ajax form form submits the file in input file

Source: Internet
Author: User

Today's mainstream browser because the AJAX submission form form can not be submitted to the background file type data for background processing, but in development for some reason and have to use Ajax to submit files,

To solve this problem I have gone a lot of detours:

1, with the original input file, does not support the Ajax upload files, you will say you can use the Ajax form form to upload it? But I'm going to have to call after the upload success with JS processing some dialog boxes, so this method to exclude

2, with the uploadify upload plugin, made to upload things, the results are not ideal, because you can not determine which image is uploaded, the need to judge each picture, exclude

3, finally chose Jquery.form.min.js this upload plug-in, as to how to use the online there are a lot of tutorials, I am here to list some of the problems I encountered it, for the future encounter can be quickly used (forget can quickly find)

Let's talk about the Jquery.form.min.js plugin. It is an excellent AJAX form plug-in, and we can easily use it to manipulate the values of form controls, empty and reset form controls, upload attachments, and complete AJAX form submissions. Jquery.form.min.js has two core methods Ajaxform () and Ajaxsubmit (), because I only use ajaxsubmit (), so I only introduce the application of Ajaxsubmit ().

Using Ajaxsubmit () makes the AJAX submission process of the entire form very simple, so I'll talk about the problem I'm having:

Some of the problems I encountered with Jquery.form.min.js:

3.1. Click the Submit button Yes, the dialog automatically closes the problem (implemented using the method in Jquery.form.min.js)

3.2, Judge input file upload type problem (using input tag onchange event to judge)

3.3, in IE browser input file empty problem (with JS empty)

Learn about the common properties of jquery.form.min.js with these links

Http://www.helloweba.com/view-blog-236.html

Http://www.jb51.net/article/42271.htm

The front-end code for the above three questions is posted below:

Answer to question 3.1


function Showrequest (FormData, Jqform, Options) {//completed before submission, verify that the file in input file       if (!true)       {             alert ("Password cannot be empty! ")            return false;//cannot be verified       }      Else
{ return true;//this is verified }

Answer to question 3.3

Html


<form id= "Index_form" name= "Index_form" role= "form" method= "POST" class= "Form-horizontal" enctype= "multipart/ Form-data ">      <table>
<tr> <td> Picture one: <input id= "Pic1" name= "Pic1" type= "file" onchange= "Pic1 ()"/> </td> </tr> <tr> <td> Picture II: <input id= "Pic2" name= "Pic2" onchange= "Pic2 ()" type= "File"/> </td> </tr> <tr> <td> picture three: <input id= "pic3" name= "pic3" onchange= "pic3 ()" Type= "File"/></td> </tr> </table> <input class= "btn btn-primary" value= "Submit" type= " Submit "/> </form>

Question 3.2 The answer JS here gives only one input file authentication method

Verify that the upload file is a picture format
    function Pic1 () {        var strs = new Array ();//defines an array of        var pic1= $ ("#pic1"). Val ();        STRs = Pic1.split ('. ');        var suffix = strs [STRs. length-1];        if (suffix! = ' jpg ' && suffix! = ' gif ' && suffix! = ' jpeg ' && suffix! = ' png ') {            alert ("You chose not Picture, please select the picture! ");            var obj = document.getElementById (' Pic1 ');            obj.outerhtml = obj.outerhtml; This is emptied, and can be successfully executed under IE8.
Obj.select (); Document.selection.clear (); As if this method can also empty the value of input file, but I did not test }

$ (function () {

    var options = {          URL: ' ....,, ',        beforesubmit:  showrequest,  //Pre-submission process         success:       Showresponse,  //processing completed         resetform:true,          dataType:  ' json '         };        $ (' #index_form '). Submit (function () {//Note the index_form here

Return false;//prevent dialog from turning off automatically
     });
});

How an action in MVC gets a file

httpfilecollection files = System.Web.HttpContext.Current.Request.Files;
            if (Files. COUNT<3)//This is to show an unknown error, so only upload three images to execute the following code            {                gm.id = 1;                Gm.message = "Picture not uploaded successfully!" ";                Return Json (GM);            }

The JS method to return to the front end after executing the action method successfully

function Showresponse (responsetext, statustext) {         if (responsetext.id = = 3) {              alert ("Upload succeeded");                        $ ("#My_Dialog"). Modal (' show ');//go so many detours, for is here, again open a Dialog, so did not choose to use the form action upload file
}

{

 

The following gives Ajaxsubmit () a rich set of options, which we will use as a list of possible sizes for reference.

Property Describe
Url The AJAX request will be submitted to the URL, which defaults to the form's Action property value
Type Specifies the method by which the form data is submitted: "GET" or "POST". Default value: The Method property value of the form (if no default is found for "GET").
DataType The type of data expected to be returned. NULL, "XML", "script", or "JSON" one of them. DataType provides a method that specifies how the server's response is handled. This is directly reflected in the Jquery.httpdata method. The following values are supported:
' XML ': if datatype = = ' xml ', the server response will be treated as XML. Also, if the "success" callback method is specified, the Responsexml value is returned.
' JSON ': if datatype = = ' json ', the server response will be evaluated and passed to the ' success ' callback method if it is specified.
' Script ': if datatype = = ' script ', the server response will be evaluated as plain text.
Default value: null (server returns RESPONSETEXT value)
Target Indicates the element in the page that is updated by the server response. The value of the element may be specified as a jquery selector string, a jquery object, or a DOM element.
Default value: null.
Beforesubmit The callback function that was called before the form was submitted. The "Beforesubmit" callback function is provided as a hook to run the pre-commit logic or to validate the form data. If the "Beforesubmit" callback function returns false, the form will not be committed. The "Beforesubmit" callback function has three invocation parameters: form data in array form, jquery form objects, and options objects in the incoming ajaxform/ajaxsubmit.
Default value: null
Success callback function that is called after the form has been successfully committed. If the "Success" callback function is provided, it is called when the response is returned from the server. The datatype option value is then determined to return the value of ResponseText or Responsexml.
Default value: null
ClearForm Indicates whether the form data is purged if the form submission succeeds. Default value: null
Resetform Indicates whether the form submission succeeds if it is reset. Default value: null

The Jquery.form plugin also provides Formtoarray (), Formserialize (), Fieldserialize (), Fieldvalue (), ClearForm (), Clearfields (), and Resetform () and other methods. Usually we can use the form validation plug-in with the Jquery.form plugin for better results.

A uploadify sample code is given below for future reference:

&NBSP;
<div id= "Index_dialog" class= "Modal Hide Fade" tabindex= "-1" role= "Dialog" aria-labelledby= "Mycaselablejh" Aria-hid Den= "true" ><form id= "Index_form" name= "Indexuploadjh_form" role= "form" method= "POST" class= "Form-horizontal" Enctype= "Multipart/form-data" > <b> please upload </b> <br/> image upload: <input id= "Uploadifyid" name = "Uploadifyid" type= "file" multiple= "multiple"/> </form> <input class= "btn btn-primary" value= "commit" t Ype= "button" onclick= "javascript:indexfunction ();"            /> </div><script type= "Text/javascript" >//Certification Required box verify function indexfunction () { if ($ ("#Pass"). val () = = "") {//password cannot be empty $ ("Pass"). Siblings ('.                Casevalidtext '). Text (' Password cannot be null '). Show ();            Return                       } var Count = $ ("#uploadifyID"). Data (' Uploadify '). Queuedata.queuelength;              if (lawyercertificatejhcount <= 0) {alert ("Please upload file");  Return        } $ (' #uploadifyID '). Uploadify (' upload ', ' * '); }//clear and close form function Clearfromcasepassdata () {//$ ("#index_form: Input"). Not (": button,: Submit,: RESET,: H Idden "). Val (" "). Removeattr (" Checked "). Remove (" selected ");    Core $ ("#index_Dialog"). Modal (' hide ');            } $ (function () {//Upload instrument Attachment Management loadfun ();//Initialize plugin})//Close upload picture form function Closepdfsee () {        $ ("#index_Dialog"). Modal (' hide '); } function Loadfun () {$ (' #uploadifyID '). Uploadify ({' swf ': '/scripts/uploa                          Dify/uploadify.swf ',//flash file path ' buttontext ': ' Browse ', ' width ': 40, Width of the button ' height ': 15,//Button text ' uploader ': '/home/getcasepas Sinfo ',//handling File Upload action ' Queueid ': ' Lawyercasefilequeue ',//queue ID ' queuesize              Limit ': 999,            The maximum number of uploaded files in the queue, default is 999 ' auto ': false,//If the file is automatically uploaded after selection, the default is True                       ' Multi ': false,//is a multi-select, the default is True ' removecompleted ': true,                 Whether to remove the sequence after completion, the default is True ' Filesizelimit ': ' 0MB ', ' Filetypedesc ': "Image Files",                Files logo can upload any file ' filetypeexts ': ' *.jpg;*.png;*.gif;*.jpeg; ',//allow uploading of file types, limit the file selection in the pop-up file box ' Onqueuecomplete ': function (event, data) {//All queues complete after event $ (' #uploadifyID                '). Uploadify (' Cancel ', ' * '); }, ' Onuploadstart ': function (file) {$ (' #uploadifyID '). Uploadify ("Settings", ' FormData ' , {' Pass ': $ ("#Pass"). Val (), Phone: $ ("#Phone"). Val (), No: $ ("#no"). Val (), Name: $ ("#name"). Val (), FileIndex:file.index      , Filelength: $ ("#uploadifyID"). Data (' Uploadify '). Queuedata.queuelength, IntCount:file.index});          }, ' Onuploaderror ': function (event, Queueid, Fileobj, errorobj) {},                    ' Onuploadsuccess ': function (file, data, respone) {data = Json.parse (data);                        if (data.id = = 2) {$ ("#index_Dialog"). Modal (' hide ');                        $ (' #IndexmediaForm '). Media ({width:500, height:600, Src:url                        });                    $ ("#newDialog"). Modal (' show ');                    } else {alert ("Upload failed," + data.message);        }                }            });     }

The Ajax form form submits a file in input file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.