简体   繁体   English

图像未通过 ajax 在 Laravel 中上传

[英]Image not uploading in laravel through ajax

Hello i am submitiing my form through ajax.您好,我正在通过 ajax 提交我的表单。

<form id="addProductForm" action="javascript:void(0)" enctype="multipart/form-data">
    <input type="hidden" id="productId">
        <div class="row">
            <label for="caption" class="col-md-4 col-form-label">Post Image</label>
            <input type="file" class="form-control-file" id="image" name="image">   
         </div>
    <div class="row ">
        <button type="submit" id="submitAddProduct" class="btn btn-primary mr-auto ml-auto" style="margin-top:15px;">Submit</button>
    </div>
</form>

This is the submit script这是提交脚本

$('#submitAddProduct').click(function(e){
    e.preventDefault();
    
    var image = $('#image').val();

    $.ajax({
        type:'GET',
        url:'/submitAddProduct',
        async:false,
        data:{
            'image' : image,
        },
        success:function(response) {
            $('#productId').val(response.msg);
        }
    });

});

In my controller,在我的控制器中,

public function submitAddProduct(Request $request){
        $data = $request->validate([
            'image' => ['required','image']
        ]);

        public function submitAddProduct(Request $request){
        $data = $request->validate([
            'image' => ['required','image']
        ]);

        // dd(request('image')->store('uploads','public'));

        $imagePath = request('image')->store('uploads','public');

        $image = Image::make(public_path("storage/{$imagePath}"))->fit(1200, 1200);
        $image->save();

        $id = Products::insertGetId($data);

        if($id){
            $arr = array('msg' => $id);
        }
        return Response()->json($arr);
    }

        $id = Products::insertGetId($data);

        if($id){
            $arr = array('msg' => $id);
        }
        return Response()->json($arr);
    }

image val is something like C://fakepath//name; image val 类似于 C://fakepath//name; I want image to be uploaded to storage/uploads in my public folder.我希望图像上传到我的公共文件夹中的存储/上传。

But i am getting errors.但我收到错误。 422 Unprocessable Entity

Please Help.请帮忙。 Thank You谢谢你

My current guess would be that your image gets stripped from the request, because it is bigger than upload_max_filesize and post_max_size allow.我目前的猜测是您的图片会从请求中删除,因为它大于 upload_max_filesize 和 post_max_size 允许的大小。 Can you try posting a very small (<100kB) image?您可以尝试发布一个非常小的 (<100kB) 图像吗?

My rationale for this is that, if the file is too big, it gets stripped.我的理由是,如果文件太大,它会被剥离。 If it is stripped, the validation rules fail, thus resulting in a 422.如果它被剥离,则验证规则失败,从而导致 422。

Edit: I just noticed you're working with GET as an HTTP verb.编辑:我刚刚注意到您正在使用 GET 作为 HTTP 动词。 Files can only be sent using POST (and PUT and PATCH, but let's leave those out for now).文件只能使用 POST 发送(还有 PUT 和 PATCH,但我们暂时不考虑这些)。

You are using GET to upload files which does not make any sense.您正在使用 GET 上传没有任何意义的文件。

  1. change the route from get to post in the routes file.在路由文件中将路由从 get 更改为 post。

  2. Change the ajax code to send POST rather than GET.更改 ajax 代码以发送 POST 而不是 GET。

  3. include the CSRF token in the ajax request:在 ajax 请求中包含 CSRF 令牌:

    • Using headers:使用标题:

      1. Add the following html meta tag to head (if it does not exists already): <meta name="csrf-token" content="{{ csrf_token() }}"> .将以下 html meta标记添加到头部(如果它不存在): <meta name="csrf-token" content="{{ csrf_token() }}">
      2. Add the header to your ajax:将标题添加到您的 ajax:
       $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } });
    • Or simply, add the token as parameter in the request itself:或者简单地,在请求本身中添加令牌作为参数:

       $.ajax({ type:'POST', ... data:{ '_token' : {{ csrf_token() }}, ... },
  4. That should do the trick!这应该够了吧!

Side note: try using named routes (easier to maintain), and I recommend using Axios.旁注:尝试使用命名路由(更易于维护),我建议使用 Axios。

By default, the resources/js/bootstrap.js file includes the Axios HTTP library which will automatically send this for you - Laravel docs默认情况下,resources/js/bootstrap.js 文件包含 Axios HTTP 库,它会自动为您发送 - Laravel docs

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

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