douba5540 2019-01-10 10:05
浏览 595

如何通过AJAX POST请求发送大文件大小,即超过1 MB?

I am trying to implement upload file through PHP and jquery ajax. I am able to do so for small files, however, when I try to upload large files it is showing "Unknown Error". My jquery code :

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');
                }
            });

My PHP code:

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
));

The post_max_size variable value is 100 MB. So, that is not the issue. If the issue is in the payload limit exceeding for a POST Request, then how to tackle the same?

  • 写回答

2条回答 默认 最新

  • dsx5201 2019-01-10 11:07
    关注

    Try with this code please :

    $(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);
        }
      })
     });
    
    });
    

    And use form like this:

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

    And About your PHP code :

    // 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]).']';
    

    And if you can't send large file size i.e more than 1 MB ... Just modify your php.ini :

    post_max_size = 256M
    upload_max_filesize = 1000M
    
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线