javascript - Laravel 中通过 Ajax 上传文件

标签 javascript jquery ajax laravel

我正在尝试通过 Laravel 中的 ajax 上传文件。

$("#stepbutton2").click(function(){
            var uploadFile = document.getElementById("largeImage");
            if( ""==uploadFile.value){


            }
            else{
                var fd = new FormData();

                fd.append( "fileInput", $("#largeImage")[0].files[0]);

                $.ajax({
                    url: '/nominations/upload/image',
                    data: fd,
                    processData: false,
                    contentType: false,
                    type: 'POST',
                    success: function(data){
                        if(data.uploaded==true){
                            alert(data.url);
                        }
                    },
                    error: function(err){
                        alert(err);
                    }
                });

            }
        });

我将文件输入传递给 php 脚本。

public function image(){

$file = Input::file('fileInput');
    $ext = $file->getClientOriginalExtension();
    $fileName = md5(time()).".$ext";

    $destinationPath = "uploads/".date('Y').'/'.date('m').'/';
    $file->move($destinationPath, $fileName);
    $path = $file->getRealPath();
    return Response::json(["success"=>true,"uploaded"=>true, "url"=>$path]);


    }

我收到的回复为

{"success":true,"uploaded":true,"url":false}

请求负载为

------WebKitFormBoundary30GMDJXOsygjL0ZS
Content-Disposition: form-data; name="fileInput"; filename="DSC06065 copy.jpg"
Content-Type: image/jpeg

为什么会发生这种情况?

最佳答案

找到答案:

 public function image(){

         $file = Input::file('fileInput');
             $ext = $file->getClientOriginalExtension();
             $fileName = md5(time()).".$ext";

             $destinationPath = "uploads/".date('Y').'/'.date('m').'/';
             $moved_file = $file->move($destinationPath, $fileName);
             $path = $moved_file->getRealPath();
             return Response::json(["success"=>true,"uploaded"=>true, "url"=>$path]);


             }

将路径分配给新变量后获取路径。

关于javascript - Laravel 中通过 Ajax 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28567300/

相关文章:

javascript - javascript 从数组中按键获取值

javascript - 如何在输入时格式化输入框文本

jquery - 选择具有指定类的第一个元素,如果没有,则选择另一个元素

javascript - jQuery 在特定位置插入字符

使用ajax的Javascript和php : why is the php not called?

javascript - 在 Ajax 加载的外部 html 中的脚本后调用事件

jquery - 使用ajax将表单字段的特定部分发送到服务器?

javascript - 需要连接d3中不同圆形填充布局的两个节点

javascript - 用逗号分隔的 ngTable 过滤器

javascript - 在 html 元素上使用 jQuery ReplaceWith