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

后端 未结 5 1743
温柔的废话
温柔的废话 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=$('').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

提交回复
热议问题