简体   繁体   中英

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.

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:

/**
 * @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"

    <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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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