douxiong2999 2016-06-18 15:11
浏览 61

无法使用ajax上传多个文件

First of all this might be a silly question as there are many topics available on this but seriously I am not being able to get it straight and understand how to make it work.

WHAT I AM TRYING TO DO

I am trying to upload multiple files using AJAX and PHP.

PROBLEM

  • I cant figure out how to pass the data to the PHP script using AJAX. I don't want to use a form and a submit button for uploading.
  • Tried using a form and submitting it using jQuery still couldn't make it.

HTML

<div id="content">
    <div id="heading">Upload your files seamlessly</div>
    <a href="#"><div id="upload" class="button" title="Upload your files"><i class="fa fa-cloud-upload fa-align-center" aria-hidden="true"></i>
</div></a>
    <a href="view.php"><div id="view" class="button" title="View all files on my cloud"><i class="fa fa-eye fa-align-center" aria-hidden="true"></i>
</div></a>
</div>

<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" multiple name="uploadfile[]" id="uploadfile" />
</form>

JS

<script type="text/javascript">
$(document).ready(function(){
    $('#upload').click(function(){
        $('input[type=file]').click();
        return false;
    });

    $("#uploadfile").change(function(){
         //submit the form here  
         $('#fileupload').submit();
    });
});
</script>

PHP

<?php
if(isset($_FILES['uploadfile'])){

    $errors= array();

    foreach($_FILES['uploadfile']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['uploadfile']['name'][$key];
        $file_size =$_FILES['uploadfile']['size'][$key];
        $file_tmp =$_FILES['uploadfile']['tmp_name'][$key];
        $file_type=$_FILES['uploadfile']['type'][$key]; 
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }       

        //$query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";

        $desired_dir="storage";

        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }

            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
            }
            else{                                   // rename the file if another one exist
                $new_dir="$desired_dir/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
         //mysql_query($query);         
        }
        else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}
?>

Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • dongwen9947 2016-06-19 21:25
    关注

    This is a very simple example of what you want to do.

    HTML

    Wrap your inputs within a form. Why? Because it is the easiest way to do it.

    <form action="process.php" method="post">
        <input type="file" multiple name="uploadfile[]">
        <input type="submit" value="Upload"> 
    </form>
    

    JavaScript

    Attach an onsubmit event handler to your form. Use $.ajax() to send a POST request.

    Pass your form element i.e. this into the constructor of a FormData object and use it as your data when you send the request as shown below. You need to make sure that you set processData and contentType as false also for this to work.

    $(function () {
        $('form').on('submit', function (e) {
            e.preventDefault();
            // send request
            $.ajax({
                url: this.action, 
                type: this.method, 
                data: new FormData(this), // important
                processData: false, // important 
                contentType: false, // important
                success: function (res) {
                    alert(res);
                }
            });
        });
    });
    

    PHP (process.php)

    Let's clean up your PHP.

    <?php
    // always a good idea to turn on errors during development
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    $dir = './storage';
    $errors = [];
    
    if (isset($_FILES['uploadfile'])) {
        $files = $_FILES['uploadfile'];
        // create directory if it does not exist
        !is_dir($dir) && mkdir($dir, 0700);
        // validate & upload files
        foreach (array_keys($files['tmp_name']) as $key) {
            $file = [
                'name' => $files['name'][$key],
                'size' => $files['size'][$key],
                'tmp_name' => $files['tmp_name'][$key],
                'type' => $files['type'][$key],
                'error' => $files['error'][$key]
            ];
            // skip if no file was given
            if ($file['error'] === UPLOAD_ERR_NO_FILE) {
                continue;
            }
            // get file extension
            $file['ext'] = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            // generate a unique name (!)
            $file['name'] = uniqid() . '.' . $file['ext'];
            // validate
            if (!file_exists($file['tmp_name']) || 
                !is_uploaded_file($file['tmp_name']) ||
                $file['error'] !== UPLOAD_ERR_OK) {
                $errors[$key] = 'An unexpected error has occurred.';
            } elseif ($file['size'] > 2097152) {
                $errors[$key] = 'File size must be less than 2 MB';
            // upload file
            } elseif (!move_uploaded_file($file['tmp_name'], $dir . '/' . $file['name'])) {
                $errors[$key] = 'File could not be uploaded.';
            }
        }
    }
    
    if ($errors) {
        print_r($errors);
    } else {
        echo 'no errors';
    }
    ?>
    

    (!) Do keep in mind that uniqid() is actually not unique.

    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch