我试图使用ajax和symfony上传文件

时间:2017-12-10 12:20:32

标签: php jquery ajax symfony file-upload

我正在使用Symfony 2.7

我收到了这个表格

<form name="Document" method="post" action enctype="multipart/form-data">
    <div class="col-md-6">
        <input type="file" id="documento" name="Document[Ruta]" required="required">
    </div>
    <div class="col-md-3">
        <button type="button" onclick="saveDoc()" class="btn btn-success" data-dismiss="modal">Subir</button>
    </div>
</form>

和这个ajax:

function saveDoc() {
    var inputFile = document.getElementById('documento');
    var file = inputFile.files[0];
    var data = new FormData();
    data.append('doc', file, file.name);
    $.ajax({
        url: "{{ path('fileupload') }}",
        type: "POST",
        data: {'data': data},
        processData: false,
        contentType: false,
        cache: false
    });

}

使用这个symfony控制器:

public function fileUpload(Request $request)
{
    $file = $request->files->get('doc')->getClientOriginalName;
    $user = $this->getUser();

    $filename = md5(uniqid()).'.'.$file->guessExtension();

    $request->files->get('doc')->move(
        $this->getParameter('upload_directory'),
        $filename
    );
    $document = new Document();
    $document->setRuta($filename);
    $document->setIdUser($user);
    $document->setFechaCreacion(new \DateTime("now"));
    $em = $this->getDoctrine()->getManager();
    $em->persist($document);
    $em->flush();

    return new JsonResponse(true);

}

但是我收到了这个错误:

  

注意:尝试获取非对象的属性   500内部服务器错误 - ContextErrorException

我看到235897个页面上传了symfony和ajax的文件,我无法理解我的代码有什么问题,请问各位帮帮我吧?

2 个答案:

答案 0 :(得分:0)

更改

$file = $request->files->get('doc')->getClientOriginalName;

$file = $request->files->get('doc');

答案 1 :(得分:0)

Change this

function saveDoc() {
    var inputFile = document.getElementById('documento');
    var file = inputFile.files[0];
    var data = new FormData();
    data.append('doc', file, file.name);
    $.ajax({
        url: "{{ path('fileupload') }}",
        type: "POST",
        data: {'data': data},
        processData: false,
        contentType: false,
        cache: false
    });

}


To

function saveDoc() {
    var inputFile = document.getElementById('documento');
    var file = inputFile.files[0];
    var data = new FormData();
    data.append('doc', file, file.name);
    $.ajax({
        url: "{{ path('fileupload') }}",
        type: "POST",
        **data: data**,
        processData: false,
        contentType: false,
        cache: false
    });

}

并在控制器中

更改 $ file = $ request-&gt; files-&gt; get('doc') - &gt; getClientOriginalName; 至 $ file = $ request-&gt; files-&gt; get('doc');