简体   繁体   English

Laravel + jQuery AJAX文件上传?

[英]Laravel + jQuery AJAX file upload?

I've been trying to get this done for over a week now and nothing seems to work. 我已经尝试完成一个多星期了,似乎没有任何效果。 Users are supposed to be able to upload a file to the server with a name, but somehow AJAX is not sending anything. 用户应该可以使用名称将文件上传到服务器,但是AJAX却不发送任何内容。

This is the form where a user uploads the file: 这是用户上传文件的形式:

        <div class="data-attachment" data-id="">
            <div class="new-attachment">
            <form id="form-attachment" name="newAttachment">
                <input type="text" class="attachment-name" name="name" placeholder="Name">
                <input id="file" type="file" name="file" class="attachment-name">
                <input type="submit" name="submit" value="Add attachment" id="submit">
            </form>                    
            </div>
            <button class="btn-del">
                <i class="fa fa-times"></i>
            </button>
        </div>

This is the function being called upon submission of the form: 提交表单后会调用以下函数:

        $('#form-attachment').on('submit', function (e) {
            e.preventDefault();
            form = document.forms.namedItem('newAttachment');
            formData = new FormData(form);
            reader = new FileReader();

            // data = {
            //     'name': formData.get('name'),
            //     'file': reader.readAsText($('#file')[0].files[0], 'UTF-8'),
            //     'task': $('#holder').data('id')
            // };

            console.log(formData.get('file'));

            $.ajax({
                method: 'POST',
                url: '/ajax/tasks/attachments/add',
                data: formData,
                dataType: 'json',
                processData: false,
                contentType: false,
                success: function (response) {
                    alert(response);
                    // window.location.reload();
                },
                error: function (xhr, response, error) {
                    console.log(error);
                }
            })
        });

This is the PHP code that recieves the form: 这是接收以下形式的PHP代码:

/**
 * @param Req $request
 *
 * @return void
 */
public function addAttachment(Req $request)
{
    if ($request->ajax()
        && $_SERVER['REQUEST_METHOD'] == 'POST'
        && $request->exists('file')
        && $request->exists('name')
        && $request->exists('task')
        && Auth::user()->hasRight('projects.tasks.attachments.add')
    ) {
        $oTask = Task::find($_POST['task']);
            if ($oTask) {

                Request::file('file')->store(
                    '/'.$oTask->project->id, 'local'
                );
                $oTask->attachments()->create([
                    'name' => $request->input('name'),
                    'file' => $request->file('file')
                ]);

                $oTask->project->logs()->save(
                    new Log(['description' => 'User ' . Auth::user()->nameFormatter() . ' added attachment ' . $_POST['name'] . ' to task ' . $oTask->name . ' in project ' . $oTask->project->name])
                );
            }
        }
    }

The files serve as attachments to tasks, hence the 'task' index. 这些文件用作任务的附件,因此是“任务”索引。 I've searched through multiple similar questions and tried to apply codes from the answers but nothing seems to work. 我搜索了多个类似的问题,并尝试从答案中应用代码,但似乎无济于事。 Any help or a point to the right direction is appreciated! 任何帮助或指向正确方向的方法都值得赞赏!

I see it didnt submit the file because your form is locking of enctype="multipart/form-data" 我看到它没有提交文件,因为您的表单已锁定enctype="multipart/form-data"

    <div class="data-attachment" data-id="">
        <div class="new-attachment">
        <form id="form-attachment" name="newAttachment" enctype="multipart/form-data">
            <input type="text" class="attachment-name" name="name" placeholder="Name">
            <input id="file" type="file" name="file" class="attachment-name">
            <input type="submit" name="submit" value="Add attachment" id="submit">
        </form>                    
        </div>
        <button class="btn-del">
            <i class="fa fa-times"></i>
        </button>
    </div>

also try just appending into your formData 也尝试将附加到您的formData

 if ($("#file")[0].files > 0) {
     var file = $("#file")[0].files[0];
     formData.append("file", file, file.name);
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM