jQuery upload file using jQuery's ajax method (without plugins)

后端 未结 5 1744
温柔的废话
温柔的废话 2021-02-01 23:41

At moment I want to implement picture upload without using any plug-ins.

My upload form looks like this

相关标签:
5条回答
  • 2021-02-02 00:01

    Actually there is a method to upload files with ajax (xmlhttp) with Firefox>3 and Chrome, it's also possible to upload multiple files without using forms and iframes. Actually I am making a jQuery plugin for doing this and soon I will publish it. Here is a simple example:

    var file=$('<input type=file />').get(0).files[0];
    function asyncupload(file)
    {
        var xhr = new XMLHttpRequest();    
        xhr.onreadystatechange = function() 
        {  
            if (xhr.readyState == 4) 
            {  
                if ((xhr.status >= 200 && xhr.status <= 200) || xhr.status == 304) 
                {  
                    //alert(xhr.responseText);
                }  
            }  
        };  
        xhr.upload.onload=function(e)
        {
            $('div#axprogress').progressbar("option", "value", 100);;
        };  
        xhr.upload.onprogress=function(e) 
        {  
            if (e.lengthComputable) 
            {  
                var perc = Math.round((e.loaded * 100) / e.total);  
                $('div#axprogress').progressbar("option", "value", perc);
            }  
        };  
    
        xhr.open("POST", "upload.php?filename="+file.name,true);  
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.setRequestHeader("X-File-Name", encodeURIComponent(file.name));
        xhr.send(file);  
        return xhr;
    }
    

    For getting files in server side, like php, have to do this for upload.php:

    $input = fopen("php://input", "r");
    $temp = tmpfile();
    $realSize = stream_copy_to_stream($input, $temp);
    fclose($input);
    
    if ($realSize != $this->getSize())
        {            
        return false;
    }
    
    $target = fopen($_GET['filename'], "w");        
    fseek($temp, 0, SEEK_SET);
    stream_copy_to_stream($temp, $target);
    fclose($target); 
    

    This is an simple idea example not the complete working script. Hope this helps. For more info refer to https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest

    0 讨论(0)
  • 2021-02-02 00:01
       <input type="file" id="picfile" name="picf" />
           <input type="text" id="txtName" style="width: 144px;" />
      <input type="button" value=" ADD " id="btncatsave" style="width: 75px" />
     $("#btncatsave").click(function () {
    var Name = $("#txtName").val();
    var formData = new FormData();
    var totalFiles = document.getElementById("picfile").files.length;
    
                        var file = document.getElementById("picfile").files[0];
                        formData.append("FileUpload", file);
                        formData.append("Name", Name);
    
    $.ajax({
                        type: "POST",
                        url: '/Category_Subcategory/Save_Category',
                        data: formData,
                        dataType: 'json',
                        contentType: false,
                        processData: false,
                        success: function (msg) {
    
                                     alert(msg);
    
                        },
                        error: function (error) {
                            alert("errror");
                        }
                    });
    
    });
    
     [HttpPost]
        public ActionResult Save_Category()
        {
          string Name=Request.Form[1]; 
          if (Request.Files.Count > 0)
            {
                HttpPostedFileBase file = Request.Files[0];
             }
    
    
        }
    
    0 讨论(0)
  • 2021-02-02 00:18

    AJAX or more appropriately XMLHttpRequest does not support file uploads yet. There are workarounds such as uploading through an <iframe>, but its rather cumbersome. Your time will be better spent in building your applications rather than reinventing these solutions.

    But if you're curios as to how it works internally, then feel free to checkout the source code of some of the plugins that offer this functionality. A very simple explanation can be found at this link - http://www.openjs.com/articles/ajax/ajax_file_upload/

    Basically, you change the form target to submit inside an <iframe>, thus avoiding the page refresh, and simulating AJAX, which it isn't really, but who cares - the end user can't tell.

    A minimal example for an iframe based upload may look like this:

    ​$("#upComplete").click(function() {
        // create a dynamic iframe, or use existing one 
        var iframe = $("<iframe id='f' name='f' src=''>");
        // attach a load event to handle response/ know about completion
        iframe.load(function() { alert('complete'); });
        iframe.appendTo('body');
        // change form's target to the iframe (this is what simulates ajax)
        $('#uploadForm').attr('target', 'f');
        $('#uploadForm').submit();
    });​​​​​​
    

    Note that this does not do any response handling, but just sends the picture to the server. To handle the response, a callback must be written for the iframe's load event.

    0 讨论(0)
  • 2021-02-02 00:19

    jQuery ajax does not support file uploads and implementing this manually might be cumbersome. I would suggest you looking at the jQuery form plugin.

    Of course you could always check out the source code of the plugin to see how it is implemented if you don't want to include it (it uses a hidden iFrame as files cannot be uploaded with AJAX) but why doing it if you could use it directly :-)

    Here's an example how your code might look like:

    $(function() {
        $('#uploadform').ajaxForm();
    });
    

    also make the upload button a submit button:

    <button class="btn-bl" id="upComplete" type="submit">
        <span>Upload</span>
    </button>
    
    0 讨论(0)
  • 2021-02-02 00:22

    Whilst you could create a multipart/form-data request body yourself to include a file upload field, it's not going to help you because you cannot read client-side files from the file upload field.

    (Except using the FileList interface, but currently only Firefox supports that.)

    0 讨论(0)
提交回复
热议问题