【问题标题】:Sending PDF file to server (PHP LARAVEL) using AJAX使用 AJAX 将 PDF 文件发送到服务器(PHP LARAVEL)
【发布时间】:2016-12-18 00:30:03
【问题描述】:

我正在尝试通过 AJAX 将文件 (PDF) 上传到我的服务器,以由 laravel 项目中的 php 脚本处理。我无法让文件在服务器上发送和接收。

在网络中我可以看到 POST 请求得到了 200 响应,但是它返回了 'file not present' 的响应,这是来自 laravel 的响应。

同样在 post 请求中,Request Payload 包含以下内容

------WebKitFormBoundaryliAmA3wxs0bB32iZ--

请看下面的js和html和php:

html

<form enctype="multipart/form-data">
   <input type="file" id="cv" name="cv"/>
   <button id="file-send">Add</button>
 </form>

js

$('#file-send').bind('click', function () {
   $.ajax({
      url:"test",
      data: new FormData($("#cv")[0]),
      type:'POST',
      processData: false,
      contentType: false,
      success:function(response){
         console.log(response);
      },
   });
});

LARAVEL 代码

public static function uploadingFile(){
        if (Input::hasFile('cv'))
{
   return "file present";
}
else{
    return "file not present";
}

【问题讨论】:

标签: javascript php jquery ajax laravel


【解决方案1】:

试试这个:

JS:

$('#file-send').on('click', function() {
        var file_data = $('#pic').prop('files')[0];
        var form_data = new FormData();
        form_data.append('file', file_data);

        $.ajax({
                url         : 'upload.php',     // point to server-side PHP script 
                dataType    : 'text',           // what to expect back from the PHP script, if anything
                cache       : false,
                contentType : false,
                processData : false,
                data        : form_data,                         
                type        : 'post',
                success     : function(output){
                    alert(output);              // display response from the PHP script, if any
                }
         });
         $('#pic').val('');                     /* Clear the file container */
    });

PHP:

<?php
    if ( $_FILES['file']['error'] > 0 ){
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
        {
            echo "File Uploaded Successfully";
        }
    }

?>

【讨论】:

    【解决方案2】:

    试试这个插件上传文件

    http://malsup.com/jquery/form/#file-upload

     var options = { 
                                beforeSubmit:  showRequest,   
                                success: showResponse,
                                dataType :'json'                 
                            }; 
    
        $('#file-send').ajaxSubmit(options); 
    
    function showRequest()
    {
       //before uploading file
    }
    
    function showResponse()
    {
       //response after uploading file
    }
    

    【讨论】:

      猜你喜欢
      • 2021-09-11
      • 1970-01-01
      • 2014-09-09
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 2013-11-04
      • 2016-01-18
      • 1970-01-01
      相关资源
      最近更新 更多