简体   繁体   English

如何通过 Laravel 8 中的 ajax 上传图像?

[英]how to upload an image via ajax in Laravel 8?

I've a html page with a form with some input, including a file.我有一个 html 页面,其中有一个带有一些输入的表单,包括一个文件。

I'm trying to post and save this to a API endpoint done in Laravel 8, but I can't get the data inside the controller.我正在尝试将其发布并保存到在 Laravel 8 中完成的 API 端点,但我无法在 controller 中获取数据。

My html/JS is:我的 html/JS 是:

<form class="row align-items-center g-1 product-edit-form" id="product-edit-form" enctype="multipart/form-data">
    <div class="col-6 offset-3">
        <label for="product-edit-form__code">Codice</label>
        <input type="text" disabled class="form-control-plaintext" name="code" id="product-edit-form__code" value="11111" required>
    </div>
    <div class="col-6 offset-3">
        <label for="product-edit-form__quantity">Quantità</label>
        <input type="number" class="form-control"  name="quantity" id="product-edit-form__quantity" value="10" step="1" required>
    </div>
    <div class="col-5 offset-3">
        <label for="product-edit-form__image_input" class="form-label">Immagine</label>
        <input class="form-control form-control-sm" name="image" id="product-edit-form__image_input" type="file" accept="image/*"  required>
    </div>
    <div class="w-100"></div>
    <div class="col-6 offset-3">
        <button type="submit" class="btn btn-primary mt-5">Aggiorna prodotto</button>
    </div>
</form>
<script>


  const productEditFormSubmit = async (e) => {
    e.preventDefault();
    let formData = new FormData();

    formData.append('fileData', e.target.elements.image.files[0]);
    formData.append('name', e.target.elements.quantity.value);

    try {
      // Set API url.
      const apiUrl = 'http://localhost:8000/api/product/11111?XDEBUG_SESSION_START=PHPSTORM';
      // Create options for the fetch function.
      const options = {
        method: 'PATCH',
        body: formData,
        dataType: 'json', // also tried without 
      };

      // Get a response from the API.
      const response = await fetch(apiUrl, options);
      // Parse response into JSON.
      return await response.json();
    }
    catch (error) {
      // Print catched error to the console.
      console.log('(App) Error occured while getting data.', error);
    }
  }

  document
    .querySelector('#product-edit-form')
    .addEventListener("submit", productEditFormSubmit, false);

</script>

The method in the controller: controller中的方法:

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Product $product, Request $request)
    {
        $test = $request->allFiles(); // empty
        $test2 = $request->all(); // empty
        $test3 = $request->file('fileData'); // empty
        $test4 = $request->getContent(); // string with bad data
    }

I've tried to look for the various answer on Stackoverflow and internet about.我试图在 Stackoverflow 和互联网上寻找各种答案。 Pretty much every one say to use FormData to pass the data but no one works, when I try to get the value inside the controller returns null\empty.几乎每个人都说使用FormData来传递数据,但没有人工作,当我尝试获取 controller 中的值时返回 null\empty。 I've tried to post the form both with pure JS and Jquery.我尝试使用纯 JS 和 Jquery 发布表单。 The user is anonymous.用户是匿名的。

Please note: $request->getContent() returns a string with "bad" formatted data, where at least I can get the reference\value of "quantityField" - the other is certainly the file data.请注意: $request->getContent()返回一个带有“坏”格式数据的字符串,其中至少我可以得到“quantityField”的引用\值——另一个肯定是文件数据。 Therefore, the data is passed to the backend.因此,数据被传递到后端。 How can I actually get it in a working way?我怎样才能真正以一种有效的方式得到它? (and save to a file\inside the server?) (并保存到服务器内的文件中?)

Content-Disposition: form-data; name="fileData"; filename="myw3schoolsimage.jpg"
Content-Type: image/jpeg

���� JFIF   d d  �� Ducky     <  �� Adobe d�   �� �         





��  � h �� �                                 a!1AQq��"�S���2BR#T�3�br���V�s$dt����        !1Qq���2RAa"�#����Bbr��   ? �� >;��ב���Lߝl;WX��_� A�T⇭�p\�e�%4,^w��>�����Ũ̇j)�D�``��5�ۧ�������ۧ�������ۧ�������ۧ�������ۧ�������ۧ�������ۧ�������ۧ�������ۧ�������?����gx=k�WQ8��C���yv��t� �����tV'j�%w��*�qJB5!��m���!��T
@�=m�䮌���<Eܕ��T��B>a��-6�� Gs��_O�V�|!p
>��\O�.�� ���i���4�B�|!p
>�͋R��zX��$;O_L�#)��f�"�ꁱ޴��W�.w���������a��\M�.�� �a�i���4�B�L|8����Jf�
k}9ۋ�hl!)
�{>�#\X�ހ�]��?xkbi���7zď^����Gr�I�;`���BX�����I[v�[��:|��H���Bww�����j�қy�QI>��3������8�S���Њ�u����7ն�vhq�at�M̲�}T��Q�����$�
�O=�{2�p���Q��/���j4�E.�� �a�i���4�B�l!p2S۞��j��gy奶�9�(�9�R�;cdm:��h���?����%�}\\p�����$;#�ōB)+��k��U�÷�m۪YV�Ά3 �   G�\���{8��ݎ��!��o��P�ږg2ژ�(8e���G�d�"������m�o�4�[�*:�Ks
>��+@$���3&x��vm����%2E�ͥ��v�S`���n��߼�PR�s�>c�f�r��Y˻��X��xP�p�WT�B"��<�Z���CI��2���a���R���� 9�ap.��_O����� ";�� �w�ZҚ�Z>_u�����>�Ie��YFiL�r�8����
�t�En�nT�]��r��KU�(��ZXXN`.#����I�.������� �W��v�~�� е�%�+��nG�[v�����9�:�*�9�9r��&[��IQ������,cĻ9j~�yڂÓ���r�R��J:�=    p�9'xmz�㮶�����N�pS*3mCʟ�<���Y�4�l#�$;l�{ݶ�4��������-()s���)�F�&D�GWG�49{�m���|ܳ �k�5�,�P|��^G3��8e=L��a;�'�m������:KX/��fb���>�? 1�r�ny�D�N�}��a��VF�J�� ����D�Ys��+Umª�BJ�yLj��~����V�I�Q٫�\
��;R�2i
Y'Ȑa��T����*��ѮRtt�EM�ik�%��9�y��r��\K�[ږ"�/x3wz��P�.vꇛ(<�e.(!iU���v�9E���a    �
˳���-]i��o�/��u�c��7϶�UI �
>mδ�¯��?+7��_��_�xW�ȴ�퍝`�T�f�O�nK�P���˖ew`8G?��"�H�qޖz
�Ga}`Tդ���V�e�B�s�����M�#�c|_�EL��gط-"i�,����d�ʮ<����m��
Ƽ�I3��kd���'���8��E���a�X�SCk�M5:L�Lʔ��KQ��q1�b�j�TE�@�aެ�ۜ۴.VՌ��I��'�A�s���|�:�i�Q�ۏ���"�e!��;qC�,�V�����{|^E�j;� @�vr��s��R��j�}M��R����6G�iѩ?'ĚY�d�Ӷ���h��îںK8�II'�(���ɥI���S7�M�$�_S��͹y��#���~�M���-���ժ�e\C��b��)�8���j�V���W5*���r���:��+qՒT��Lt����ޥI���f�ma��Ʉ !�(��a\����ۜ�
�W.��D���t��ꞧ�2�S�����:yY7�������ŵ��ZW�WQ�`���3�8[�u�j�V���W�6�)�V��R֢I$�$���Ĩ�|".ʞ� �锕1s�o �@y� ;%9J7��"�)v�R����z˕R-�T�:Z�s�'�`p���-�$���-<w����Yrܗ&)P��C�*RP��+%KR�B@��b�L�Q闉�50/l�5lR2Y����M�4��瘡D'�=��QT�}
?A��y���Լ�Y�}�K/���e3�$�)��7ŲnV���z4�t�A��N��]='@:�X&���8�����S�ˌ��[L�J4��
4��Ƞ�;Z����K�}&�q!N~͕ �<�D��#M+s��O^��h\��MPA�z�κí��Z�J�
�]񧳚����Z4��M��2���Si���]2jj�i����Y��e��-�e%)%Kc*U��E{r�����P��G6\� ���U����=���Ǝ]kĊ��c�[����B��A<'Â���F���D�ȟB:���Ba��Z/�ՠ��T�I�o������x�������k渾�ݧJ��B��M�T�
T�JPRq������Z�\����x��kn��֩��KO�Z� I�gC�(ʆf�[�ln��5(�����#��ZhMF4�V�U�q5u��!���Q�eY�x�<3��ݗ:�KT���č��KIGj�,��J�ƪ��f�\��TϬ�;Di��F�h����A)���
�Ҋ6m���LU�]@KjQ閲$ �UG������
�ƛJW:��4���{5��Ž5.7QT��*}(IKt�+J�fW*$y"!�ōR4��Nu�QQ���F���
MC4�UK�E6���>� (���\�O�A�N�JRn��^/��Ί�D��j�LΖ��H 2���fI�8d#[�Gt�E[��1]K�@ � ����;��me���S��TVۉ��g�r�.�#���ᛒU���L�Q��GQR�����V����kE�Zs�����H���~]9Md��W�/�{�!�)����G��%$�Y�G^P>o]� ���|�v� v��L� �=H��B�2TA
��!P*   �����v۪򥱖���    �B���c�r�s�c��p����2'ͺۨK�,-�qJ�A`Dz��IUj�i��K�D��p��$�eX��h�����eOT��ZO�Z�H��re��t@�w���u=��JhC͗\"E��LyM� 7�ӎ<~K�_N�nU#���t���T%��Zg�Vs��Tt���y��}���Y"�  , @ J qIq�ђi*]b|�kRA�cl[����q�d�~wf�"_0z^Y<r�)��ț������^z��}������d�9�ɹu�8�ҹUy�aeo"r�@�� N5�bs��R�dn����MU2��{c,��.$v*]��ǰ漩n>��5�k(ԮklWJ'KU4�J�bd��L���������|����r�d�#?i��.�E��{��&�/�]�P4U^�~ɇ���c

W�_�a�2�e�������&�/�]�P4U^�~��D�L��v1@�����'�i��.�(.��ܯ�0��}2�d�45>�~ɇ���c"�zK-ʭ���R� }_�R�=�i�(�h�hlߔ�����C*�)l|{Tc�r�S���~��[���Y��Q@�V����|��%��.Ĵ�Ҏ�ZK�-�p��4�B�\"m�д�д�ZK�-���}a�>�E+�+m\R����>��`��FJ0�4WT�2�,RkVZ|"��|!@.�ZHi���4�B�.�ZO�- QLI�'�����VZ���?����� _�O���v(av�R؞P�ޞ?TU�hP��/6��*�b���~�<�Y�Q�X��Py�ah
0]>6��a@�|!h
>�����5*��y���0�&e))&Qz��]�|�[�=������$�x��> P߮O��p���G�Q4ә�#�
 
���0���%��v�τ( ��9�N 3�\!@d�����Zt�(HL�=ŀ�" p�� 8@ �� � � p� ��
------WebKitFormBoundaryB1hchGuFjUbD9Br4
Content-Disposition: form-data; name="quantityField"

10
------WebKitFormBoundaryB1hchGuFjUbD9Br4--

I would try this:我会试试这个:

$.ajax({
    type: 'POST',
    url: 'action',
    data: data,
    enctype: 'multipart/form-data', //<---
    // continue ...

Can you add this line to your header, please!请将此行添加到您的 header 中!

'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'

  const options = {
    method: 'PATCH',
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
    body: formData,
    dataType: 'json', // also tried without 
  };

I would prefer to set the method to POST.

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

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