donglu5047 2017-07-26 12:05
浏览 27

AJAX到PHP图像上传

I am attempting to upload multiple images from AJAX to PHP. Here's a run down of what I have so far.

HTML

<form>
    <input class="images" type="file">
</form>

There could be more than one input field if the user has multiple images to upload.


Javascript

var imageObject = GetAllFiles($('.images'));

function GetAllFiles(_selector)
{
     var newObject = {};

     for (var i = 0; i < $(_selector).length; i++)
     {
         var elem = $(_selector)[i];
         newObject[i] = $(elem).files;
     }

     return newObject;
 }

 $(document).on('click', '#submit', function() {
     var _data = JSON.stringify(imageObject);
     $.post('upload.php', { action: 'ImageUpload', data: _data }, function (e){
         alert(e);
     });
 )};

Send data via AJAX after conversion to JSON


PHP

if(isset($_POST['action']))
{
    $action = $_POST['action'];

    switch($action)
    {
        case 'ImageUpload' : ImageUpload($_POST['data']); break;
    } 
}

function ImageUpload($jsonData)
{
    $images = json_decode($jsonData);

    foreach($images as $image)
    {
        $directory = "../images/maschine/";
        $target_file = $directory . basename($_FILES[$image])['name'];

        if (move_uploaded_file($_FILES[$image]["tmp_name"], $target_file))
        {
            echo('Success');
        } else 
        {
            echo('Failure');
        }
    }
}
  • 写回答

1条回答 默认 最新

  • dongwei2882 2017-07-26 12:18
    关注

    Add id in the file input first, and remember the enctype='multipart/form-data' in form.

    <input class="images" name="file[]" type="file" multiple>
    

    after that in the script

    <script>  
    $('YoursubmitbuttonclassorId').click(function() {
    var filedata = document.getElementsByName("file"),
            formdata = false;
    if (window.FormData) {
        formdata = new FormData();
    }
    var i = 0, len = filedata.files.length, img, reader, file;
    
    for (; i < len; i++) {
        file = filedata.files[i];
    
        if (window.FileReader) {
            reader = new FileReader();
            reader.onloadend = function(e) {
                showUploadedItem(e.target.result, file.fileName);
            };
            reader.readAsDataURL(file);
        }
        if (formdata) {
            formdata.append("file", file);
        }
    }
    if (formdata) {
        $.ajax({
            url: "/path to upload/",
            type: "POST",
            data: formdata,
            processData: false,
            contentType: false,
            success: function(res) {
    
            },       
            error: function(res) {
    
             }       
             });
            }
      });
     </script>
    

    In the php file

     <?php
      for($i=0; $i<count($_FILES['file']['name']); $i++){
        $target_path = "uploads/";
        $ext = explode('.', basename( $_FILES['file']['name'][$i]));
        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 
    
         if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
            echo "The file has been uploaded successfully <br />";
         } else{
             echo "There was an error uploading the file, please try again! <br 
         />";
         }
       }
      ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向