dpd66100 2015-09-13 06:43
浏览 78

ajax - 如何上传多个文件

I'm stuck and need your help - I have designed a simple form which allows the user to upload comment text and files to the server. When the form is submitted, the file upload process is handled in 'upload.php' file. It works perfectly fine for uploading only 1 file.

I would like my script to be able upload multiple files with AJAX.

This is what I did so far -

HTML (part of it):

<input type='file' name='file[]' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" />
<input type='file' name='file[]' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" />
<input type='file' name='file[]' maxlength='1' accept="image/jpg,image/png,image/jpeg,image/gif" />

JS

$(function() {
    $(document).on('submit','form',function(e) {
        e.preventDefault(); 

    var $form = $(this);
    var file_data = $form.find('.file-field').prop('files')[0];   
    var form_data = new FormData();       
    form_data.append('act', act);
    form_data.append('comment[text]',  $form.find('.comment-field').val());   
    form_data.append('comment[pageName]',  $form.find('.pagename-field').val());   

    form_data.append('file[]', file_data);



    $.ajax({
           type: "POST",
           url: "ajax/addComment.php",

           dataType: 'text',  
           cache: false,
           contentType: false,
           processData: false,  
           async: false,
           data: form_data,
           success: function(data)
           {
                $("#loader").hide();
                $('#commentsBox'+$form.find('.refid-field').val()).prepend(data);
                 $("form").reset(); 

           }

         });

    return false; 

    });
});
  • 写回答

3条回答 默认 最新

  • dotwc62080 2015-09-13 07:22
    关注

    You can not upload files using Ajax. You will have to have form attribute enctype="multipart/form-data" and submit the form using normal html request. To avoid the page refresh you can use iframe.

    There are jquery plugins like https://blueimp.github.io/jQuery-File-Upload/ integrating with php you can solve your problem

    评论

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂