【问题标题】:How to send large file size i.e more than 1 MB through AJAX POST Request?如何通过 AJAX POST 请求发送大文件,即超过 1 MB?
【发布时间】:2019-01-10 10:05:37
【问题描述】:

我正在尝试通过 PHP 和 jquery ajax 实现上传文件。我可以对小文件执行此操作,但是,当我尝试上传大文件时,它显示“未知错误”。 我的jQuery代码:

var data = {
    data: self.parent().prev().find('img').attr('image_data'),
};
$.ajax({
            url: 'banner_data/upload_remove_files',
            type: 'POST',
            data: data,
            dataType: "json",
            success: function(data) {
                if (data.msg != 'error' && self.hasClass('remove_class')) {
                    alert('File Uploaded');
                },
                error: function() {
                    alert('Unknown error occurred');
                }
            });

我的 PHP 代码:

if (!empty($_POST['data'])) {
    $file_location = $_SERVER['SERVER_NAME'].
    '/pathname';
    $file_name = !empty($_POST['name']) ? $_POST['name'] : '';
    list($type, $raw_data) = explode(';', $_POST['data']);
    list(, $raw_data) = explode(',', $raw_data);
    $raw_data = base64_decode($raw_data);
    if (file_put_contents($file_location.$file_name, $raw_data) === FALSE) {
        $msg = 'error';
    }
}
print json_encode(array(
    'msg' => $msg,
    'file_name' => $file_name
));

post_max_size 变量值为 100 MB。所以,这不是问题。 如果问题在于 POST 请求的负载限制超出,那么如何解决?

【问题讨论】:

  • 您在控制台中只得到Unknown Error 作为错误?这是不可能的。
  • 你重启服务器了吗? stackoverflow.com/a/11853729/2181514
  • 检查控制台中的实际错误。 Unknown error 消息来自您自己的代码,根本没有帮助。
  • 看起来有许多设置需要设置,例如upload_max_filesize stackoverflow.com/a/42731244/2181514(以及该问题的其他答案)
  • @RoryMcCrossan 的好消息 - 将您的 error 处理程序更改为 error: function(jqXHR, textStatus, errorThrown) { console.log(jqXHR, textStatus, errorThrown); } 并检查控制台。

标签: php jquery ajax post


【解决方案1】:

添加 mimeType 以使用 ajax 进行文件发送

$.ajax({
    url: 'banner_data/upload_remove_files',
    type: 'POST',
    data: data,
    mimeType: "multipart/form-data",
    contentType: false,
    cache: false,
    processData: false,
    dataType: "json",
    success: function(data) {
        if (data.msg != 'error' && self.hasClass('remove_class')) {
            alert('File Uploaded');
        }
    },
    error: function() {
        alert('Unknown error occurred');
    }
});

【讨论】:

    【解决方案2】:

    请尝试使用此代码:

    $(document).ready(function(){
    
     $('#your_form').on('submit', function(event){
      event.preventDefault();
      $.ajax({
       url:"banner_data/upload_remove_files",
       method:"POST",
       data: new FormData(this),
       dataType:'JSON',
       contentType: false,
       cache: false,
       processData: false,
       success:function(data)
       {
        if(data.msg != 'error' && self.hasClass('remove_class')) {
          alert('File Uploaded');
        }
        },
       error:function(data){
        console.log(data);
        }
      })
     });
    
    });
    

    并使用如下形式:

     <form id="your_form" method="POST" enctype="multipart/form-data">
        <input type="file" name="image">
        <input type="submit" name="submit" value="Upload">
     </form>
    

    关于你的PHP代码

    // SET A DEFAULT VALUES
    $msg = 'error';
    $result = '';
    
    if (isset($_POST['submit'])) {
            $file = $_FILES['file'];
            $fileName = $file['name'];
            $fileTmpName = $file['tmp_name'];
            $fileSize = $file['size'];
            $fileError = $file['error'];
            $fileType = $file['type'];
            $fileExt = explode('.', $fileName);
            $fileActualExt = strtolower(end($fileExt));
    
            # VERIFY YOUR FILE HERE
    
            if ($fileError != 0) {
                $msg = "error";
            }
    
            # UPLOAD ...
            clearstatcache();
            $fileNewName = uniqid(true).".".$fileActualExt; // GENERATE NAME FOR THIS FILE
            $fileDestination = 'your_path/'.$fileNewName;
    
    
            if (move_uploaded_file($fileTmpName, $fileDestination)) {
                $msg = "Good ...";
                $result = "File Path : ".$fileDestination;
            }
    }
    
    echo '['.json_encode(['msg' => $msg, 'file_name' => $result]).']';
    

    如果您不能发送大文件大小,即超过 1 MB...只需修改您的 php.ini

    post_max_size = 256M
    upload_max_filesize = 1000M
    

    【讨论】:

    • 我建议您直接尝试使用文件,例如不使用 AJAX 上传图像,然后查看是否有任何错误...
    猜你喜欢
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-30
    • 2017-10-09
    • 2023-03-19
    相关资源
    最近更新 更多