如何上传文件在jquery和HTML中使用复杂的输入表单

时间:2016-08-25 09:33:07

标签: javascript php jquery html forms

我知道这么多重复的问题。但我不知道,如何以复杂的形式上传表格中的数组。这是我的HTML: enter image description here 这个jquery:

function saveDraft(){
        var scope = $('#scope').val();
        var secrecy = $('#secrecy').val();
        var priority = $('#prio').val();
        var cc = $('#cc').val();
        var subject = $('#form-field-subject').val();
        var msg = $('.wysiwyg-editor')[0].innerHTML;
        var attachment = document.getElementById('attachment');
        var refnd = $('#refnd').val();
        var refarsip = $('#refarsip').val();
        var from = $('#from').val();
        var approval = []; 
        $('.approval :selected').each(function(i, selected){ 
          approval[i] = $(selected).val(); 
        });
        var receiver = []; 
        $('.for :selected').each(function(i, selected){ 
          receiver[i] = $(selected).val(); 
        });
        $.ajax({
            type: 'post',
            url: '<?php echo $this->baseurl; ?>/memo/saveDraft',
            data: {
                scope : scope,
                secrecy : secrecy,
                priority : priority,
                from : from,
                approval : approval,
                receiver : receiver,
                cc : cc,
                subject : subject,
                msg : msg,
                attachment : formData,
                refnd : refnd,
                refarsip : refarsip
            }

1 个答案:

答案 0 :(得分:1)

试试这个:

HTML:

<input id="pic" type="file" name="pic" />
<button id="upload">Upload</button>

JS:

$('#upload').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

        $.ajax({
                url         : 'upload.php',     // point to server-side PHP script 
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
         $('#pic').val('');                     /* Clear the file container */
    });

腓:

<?php
    if ( $_FILES['file']['error'] > 0 ){
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
        {
            echo "File Uploaded Successfully";
        }
    }

?>

这会将单个文件上传到服务器。进行一些更改,以便您也可以上传多个文件。