isuifeng

用jquery的ajax实现简单的文件上传功能,并且限制文件大小,先上代码。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>test</title>
    <script src="https://cdn.bootcss.com/jquery/3.1.1/jquery.js"></script>
</head>
<body>
    
    <form id="uploadForm" enctype="multipart/form-data">
        <input id="file" type="file" name="file"/>
        <button id="upload" type="button">上传</button>
    </form>
    
    <script>
        
        var maxSize = 1000;//文件上传大小限制
        $(\'#upload\').click(function(){
            var size = document.getElementById(\'file\').files[0].size;
            var filesize = (size / 1024).toFixed(2);
            
            if(filesize < maxSize){
                $.ajax({
                    url: \'/upload.php\',
                    type: \'POST\',
                    cache: false,
                    data: new FormData($(\'#uploadForm\')[0]),
                    processData: false,
                    contentType: false
                }).done(function(res) {
                    alert(\'上传文件成功\');
                }).fail(function(res) {
                    alert(\'上传文件失败\');
                }); 
            }else{
                alert(\'上传文件不许大于\' + maxSize + \'KB\');
            }            
        });
    </script>
</body>
</html>
  
  

上传是使用FormData对象来实现,利用files[0].size属性来获取文件的大小,进行上传限制。

分类:

技术点:

相关文章: