简体   繁体   English

使用Ajax在php中上传(.doc,.docx)文件

[英]Upload (.doc, .docx) file in php using ajax

I'm trying to upload a .doc, .docx file via ajax but it keeps on sending me an error in my console. 我正在尝试通过ajax上传.doc, .docx文件,但是它一直在向我发送错误消息。 Here is my script. 这是我的剧本。

        var file = $('#file').val();
        $(document).on('change','#file',function(){
            var data = new FormData($("#fileinfo"));
            $.each($('#file')[0].files, function(i, file) {
                data.append('file-'+i, file);
            });
            console.log(FormData);
            $.ajax({
                url: "main-function.php?call=upload",
                data: data,
                cache: false,
                contentType: false,
                processData: false,
                type: 'POST',
                success: function(data){
                    console.log(data)
                }
            });
            return false;

        });

And here is main-function.php : 这是main-function.php

   if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
    die("Upload failed with error " . $_FILES['file']['error']);
    }
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime = finfo_file($finfo, $_FILES['file']['tmp_name']);
    $ok = false;
    $userid = $_SESSION['username'];
    switch ($mime) {       
       case 'application/pdf':
       case 'application/msword':
            $ok = true;
            move_uploaded_file($_FILES["file"]["tmp_name"],
              "pds/" . $userid . '-' . time().'-' . $_FILES["file"]["name"]);
             break;
       default:
           echo 'Type not supported';
    }

Edit: Here is the error 编辑:这是错误

  <b>Notice</b>:  Undefined index: file in <b>C:\xampp\htdocs\hrms\main\main-function.php</b> on line <b>9</b><br />

  <b>Warning</b>:  finfo_file() [<a href='function.finfo-file'>function.finfo-file</a>]: Empty filename or path in <b>C:\xampp\htdocs\hrms\main\main-function.php</b> on line <b>9</b><br />

You are sending files as file-0 , file-1 , ... but you are looking for file . 您正在将文件发送为file-0file-1 ,...,但是您正在寻找file
If you're only sending one file just send the file as file 如果您只发送一个文件,只需将该文件作为file发送

data.append('file', $('#file')[0].files[0]);

also if #fileinfo a form, you'll want to pass it to FormData constructor not a jQuery object 同样,如果#fileinfo是一个表单,则需要将其传递给FormData构造函数而不是jQuery对象

var data = new FormData($("#fileinfo")[0]);

also if #file is in that form you'll be sending the file twice. 同样,如果#file采用这种格式,则您将发送两次文件。

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

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