Загрузить изображение с помощью модального - PullRequest
0 голосов
/ 13 мая 2019

Я хочу загрузить изображение, используя модал. Я знаю, как это сделать с помощью HTML-формы, но я не уверен, как использовать ajax-запрос для отправки данных в контроллер. Можно ли использовать контроллер, который у меня сейчас? Заранее спасибо!

Контроллер:

public function postCreatePost(Request $request)
    {

        ...
        $post->longitude = $request['longitude'];

        if($request->user()->posts()->save($post))
        {
            $message = 'Post Successful';
        };

        $file = $request->file('image');
        $filename = $post->id.'.jpg';
        if($file)
        {
            Storage::disk('local')->put($filename, File::get($file));
        }

        return redirect()->route('dashboard')->with(['message' => $message]);
    }

запрос ajax, который у меня есть:

$('#modal-save').on('click',function(){
        //create ajax request
        $.ajax({
            method: 'POST',
            url: urlEdit, //url route is defined in the dashboard html script
            //pass the post content and id to body and postId which will be used in the Post controller edit method
            //need the token to avoid error
            data: {body: $('#post-content').val(), postId: postId, _token: token}
        })
            .done(function (msg){
                //console.log(msg['message']);
                //console.log(JSON.stringify(msg));
                $(postBodyElement).text(msg['new_content']);    //update the post w/o refreshing the page
                $('#edit-post').modal('hide');  //hide the modal
            })
    });

Модал:

<div class="modal" tabindex="-1" role="dialog" id="edit-post">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Post</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form enctype="multipart/form-data">
                        <div class="form-group">
                            <label for="post-content">Edit Post</label>
                            <textarea class="form-control" name="post-content" id="post-content" rows="5"></textarea>
{{--                            copy meta data using jquery?--}}
{{--                            add a separate image form here--}}
                            <label for="image">Image (jpg only)</label>
                            <input type="file" name="image" class="form-control" id="image">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="modal-save">Save changes</button>
                </div>
            </div>
        </div>
    </div>

Ответы [ 2 ]

0 голосов
/ 14 мая 2019

Вы не отправляете изображение на сервер.Пожалуйста, используйте объект formData для отправки медиа на сервер.

/** New form data object */
var formData = new FormData();
/** append post content */
formData.append('postcontent', $('#post-content').val());
/** append post id */
formData.append('postId', postId);
/** append token */
formData.append('_token', token);
/** append image */
formData.append('image', $("input[type=file]")[0].files[0]);

При вызове ajax отправьте formData в данных

   $.ajax({
        method: 'POST',
        url: urlEdit, 
        data: formData,
        cache: false,
        contentType: false,
        processData: false
   }).done(function (msg){
        $(postBodyElement).text(msg['new_content']); 
        $('#edit-post').modal('hide');  //hide the modal
   })
0 голосов
/ 13 мая 2019

Контроллер выглядит нормально. Но вы не передаете изображение:

Попробуйте это

$('#modal-save').on('click',function(){
        //create ajax request
        $.ajax({
            method: 'POST',
            url: urlEdit, //url route is defined in the dashboard html script
            //pass the post content and id to body and postId which will be used in the Post controller edit method
            //need the token to avoid error
            data: {
              body: $('#post-content').val(), 
              postId: postId, 
              _token: token,
              image:$('#image').val()
         }
        })
            .done(function (msg){
                //console.log(msg['message']);
                //console.log(JSON.stringify(msg));
                $(postBodyElement).text(msg['new_content']);    //update the post w/o refreshing the page
                $('#edit-post').modal('hide');  //hide the modal
            })
    });

Затем вы можете получить изображение в контроллере:

if( $request->hasFile('image') ) {
    $file = $request->file('image');
    $name = time().$file->getClientOriginalName();
    $file->move(public_path().'/images/', $name);
} 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...