使用symfoy使用AJAX上载时文件未上载

时间:2019-08-01 15:24:13

标签: javascript ajax symfony file-upload

我正在开发应用程序,我想使用带有symfony 3.4的Ajax上传图片。抱歉,因为我是AJAX的新手,所以我错过了任何东西。我正在从https://codepen.io/dsalvagni/pen/BLapab

开始

我从symfony收到200响应,但是文件没有上传。

实体:

    /**
 * @ORM\Column(type="string", length=255)
 * @var string
 */
private $image;

/**
 * @Vich\UploadableField(mapping="profile_image", fileNameProperty="image")
 * @var File
 */
private $imageFile;

这是我的控制人:

 public function testAction(Request $request)
{

    $testEntry = new Test();

    $form = $this->createForm(TestType::class, $testEntry);

    $form->handleRequest($request);


    if ($form->isSubmitted() && $form->isValid()) {

        $file = $testEntry->getImageFile();
        $fileName = md5(uniqid()) . '.' . $file->guessExtension();
        $photoDir = $this->container->getParameter('kernel.root_dir') . '/../web/uploads/images';

        $file->move($photoDir, $fileName);
        $testEntry->setImage($fileName);
        $em = $this->getDoctrine()->getManager();
        $em->persist($testEntry);
        $em->flush();

        if ($request->isXmlHttpRequest()) {
            return new JsonResponse(array('message' => 'Success!', 'success' => true), 200);
        }

        if ($request->isMethod('POST')) {
            return new JsonResponse(array('message' => 'Invalid form', 'success' => false), 400);


        }

        return $this->redirect($this->generateUrl('homepage'));



    }
    return $this->render('@Alumni/Default/test.html.twig',

        ['form' => $form->createView()]);

}

这是我的html.twig

    {{ form_start(form) }}
    {{ form_errors(form) }}

    {{ form_row(form.name) }}





    <div class="profile">
        <div class="photo">
            {{ form_widget(form.imageFile, {'attr': {'class': 'file-upload'}}) }}

            <div class="photo__helper">
                <div class="photo__frame photo__frame--circle">
                    <canvas class="photo__canvas"></canvas>
                    <div class="message is-empty">
                        <p class="message--desktop">Drop your photo here or browse your computer.</p>
                        <p class="message--mobile">Tap here to select your picture.</p>
                    </div>
                    <div class="message is-loading">
                        <i class="fa fa-2x fa-spin fa-spinner"></i>
                    </div>
                    <div class="message is-dragover">
                        <i class="fa fa-2x fa-cloud-upload"></i>
                        <p>Drop your photo</p>
                    </div>
                    <div class="message is-wrong-file-type">
                        <p>Only images allowed.</p>
                        <p class="message--desktop">Drop your photo here or browse your computer.</p>
                        <p class="message--mobile">Tap here to select your picture.</p>
                    </div>
                    <div class="message is-wrong-image-size">
                        <p>Your photo must be larger than 350px.</p>
                    </div>
                </div>
            </div>

            <div class="photo__options hide">
                <div class="photo__zoom">
                    <input type="range" class="zoom-handler">
                </div><a href="javascript:;" class="remove"><i class="fa fa-trash"></i></a>
            </div>
            <button type="button" id="uploadBtn">Upload</button>

        </div>
    </div>


    {{ form_row(form.submit, { 'label': 'Submit me' }) }}
    {{ form_end(form) }}

这是我的路线

test:
path:   /test
defaults: {_controller: AlumniBundle:Default:test}

这是我的js

$(function() {

    /**
     * DEMO
     */
    var p = new profilePicture('.profile', null,
        {
            imageHelper: true,
            onRemove: function (type) {
                $('.preview').hide().attr('src','');
            },
            onError: function (type) {
                console.log('Error type: ' + type);
            }
        });


    $('#uploadBtn').on('click', function() {
        var image = p.getAsDataURL();

        $.post("/test", { image: image });

    });

,我得到200响应,但找不到文件: enter image description here

在此先感谢您的帮助

1 个答案:

答案 0 :(得分:0)

由于您的函数未发送任何文件,因此无法上传。
最多只是发送文件名。

功能

function ajaxSubmit(node) {
    $.ajax({
        type: node.attr("method"), // Method on form tag
        url: node.attr("action"), // Action on form tag
        enctype: "multipart/form-data", //needed to upload files
        data: new FormData(node[0]), // The form content
        processData: false,
        contentType: false,
        cache: false
    }).done(function(response, status, xhr) {
        console.info(response);
    }).fail(function(request, status, error) {
        console.error(request);
        console.error(status);
        console.error(error);
    });
}

动作

$(body).on("submit", ".ajs", function(e) {
    e.preventDefault(); // Prevent default HTML behavior
    ajaxSubmit($(this)); //Handle submit with AJAX
});

视图

// Add 'ajs' class to forms that should be submited with AJAX
{{ form_start(form, {'class': 'ajs'}) }}