简体   繁体   English

如何使用AJAX将所选文件传递到PHP文件?

[英]How can I use AJAX to pass selected files to a PHP file?

I have 2 forms: 我有2种形式:

  • Form A contains field name, age, address, email and a hidden text field for the names of images which are going to be uploaded in form B. 表格A包含字段名称,年龄,地址,电子邮件和用于显示将在表格B中上载的图像名称的隐藏文本字段。

  • Form B contain an input type File so users can browse and select their photos. 表格B包含输入类型“文件”,因此用户可以浏览和选择他们的照片。

  • I used Jquery to trigger an function upload those images after they are selected. 我使用Jquery触发一个函数,在选择这些图像后将其上传。

  • I'm stuck at the step passing the selected images array to the PHP file that handles upload progress via AJAX. 我被困在将所选图像数组传递到通过AJAX处理上传进度的PHP文件的步骤。

  • I searched but there were no samples for my problem. 我进行了搜索,但没有样本可以解决我的问题。 I appreicate any help. 我非常感谢您的帮助。

     <form action="upload_img.php" name="form_B" method="POST" enctype="multipart/form-data"> Select images: <input type="file" name="selected_imgs[]" id="selected_imgs" multiple> </form> <script type="text/javascript"> $(function() { $("input:file").change(function (){ ajax_upload(); }); }); </script> 

You can try below code 您可以尝试以下代码

function uploadFile(){
var file = $('#filetoupload');
var valid_extensions = /(\.jpg|\.jpeg|\.gif|\.doc|\.xls|\.txt|\.rtf|\.pdf)$/i;
var isvalid = true;
//for every file...
var input = document.getElementById('filetoupload');
for (var x = 0; x < input.files.length; x++) {
    if(!valid_extensions.test(input.files[x].name)){
        isvalid = false;
    }
}

if(isvalid == true ){ 
    var formData = new FormData();
    for (var x = 0; x < input.files.length; x++) {
        formData.append("filetoupload[]",input.files[x]);
    }

    $.ajax({
        url: 'localhost/upload.php',  //server script to process data
        type: 'POST',
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        dataType: "json",
        success:function (data){
            alert("File Uploaded");
            // data.src return from your server
            // so you can display image in page using <img> tag
        },
        error:function (data){ 
            alert("Error!");
        }
    });
}else{                
    alert("File format not supported!");
    return false;
}
return true;
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM