如何使用laravel中的ajax post请求将图像插入到db中?

时间:2023-01-26 14:43:16

Laravel view:

Laravel观点:

<form  enctype="multipart/form-data" method="post" name="imagesform" id="imagesform" >
    <input type="hidden" name="_token" value="{{ csrf_token()}}">
    <div>
        <label id="show" for="files" class="button">Upload photo</label>
        <input id="files" name="images" style="visibility:hidden;" type="file">
    </div> 
    <button type="submit"  class="save" id="saveImage" style="border-radius: 8px; padding: 5px 15px;">SAVE</button>
</form>

This is my code for uploading images(it takes place inside my bootstrap model).When I upload the image,and click on the submit button,the image should inserted into db and the same should be retrieved and displayed on the view page.

这是我上传图像的代码(它发生在我的引导程序模型中)。当我上传图像并单击提交按钮时,图像应该插入到数据库中,并且应该检索并显示在视图页面上。

Ajax code:

Ajax代码:

$("#saveImage").click(function(e){
    // var formdata=new FormData($("#imagesform")[0]);
    //alert(formdata);
    $.ajaxSetup({
        headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
    });
    $.ajax({
        url: 'saveImages/{{$dataId}}',
        type: 'POST',
        data:new FormData($("#imagesform")),
        success: function (data) {
            alert(data)
        },
        cache: false,
        processData: false
    });
    return false;
});

This is the ajax code,I have tried.But the alert of formdata shows [object FormData] and browser console shows Method not allowed exception

这是ajax代码,我试过了。但是formdata的警告显示[object FormData]和浏览器控制台显示方法不允许异常

Laravel Route:

Laravel路线:

Route::post('saveImages/{dataId}',['as' => 'saveImages','uses'=>'priceDetails@saveImages']);

Controller:

控制器:

public function saveImages(Request $imagesform,$dataId)
{
    if (Input::hasFile('images'))
    {
        $name  = $this->getImageId().".".$imagesform->file('images')->getClientOriginalExtension();   

        $image = $imagesform->file('images');        
        $resize = Image::make($image)->resize(700, 300)->encode($imagesform->file('images')->getClientOriginalExtension());
        $hash = md5($resize->__toString());

        $path = "public/" . $name;
        Storage::put($path, $resize->__toString());
    }
    $insertImages=new photosModel;
    $insertImages->imagesid=$this->getimagesId();
    $insertImages->deviceCategoryId=$dataId;
    $insertImages->uploadedImages=$name;
    $insertImages->save();
    return $this->formImages($dataId);

}

public function formImages($dataId){
    $dataId=$dataId;
    $images=photosModel::all();
    return view('addProductDetails1')->with('images',$images)->with('dataId',$dataId);
}

2 个解决方案

#1


6  

To upload files via AJAX you need to use XHR Level 2. The FormData class needs a HTMLFormElement in the constructor if you want to send its key-value.

要通过AJAX上传文件,您需要使用XHR Level 2.如果要发送其键值,FormData类在构造函数中需要HTMLFormElement。

You should use:

你应该使用:

new FormData( document.getElementById('imagesform') );

Also you could use with jQuery:

你也可以使用jQuery:

new FormData( $("#imagesform").get(0) )

Check my answer in another similar question to get more information.

在另一个类似问题中查看我的答案以获取更多信息。

UPDATE: Seeing your comments your problem is with the Laravel route too. If the error code is 500 and it is showing the message "Method not allowed" you need to check your routes in routes/web.php. Please put here the stacktrace of the error and your route file (use pastebin or similar).

更新:看到你的评论你的问题也在于Laravel路线。如果错误代码为500并且显示消息“Method not allowed”,则需要检查routes / web.php中的路由。请在此处输入错误的堆栈跟踪和路由文件(使用pastebin或类似文件)。

#2


3  

I was able to solve a similar problem by Frankensteining various suggestions from here. That link has a pile of really good information. You need to assign some options in the ajax call to false. In any case this is what worked for me:

我能够通过Frankensteining来解决类似的问题。那个链接有很多非常好的信息。您需要将ajax调用中的一些选项指定为false。无论如何,这对我有用:

HTML

HTML

<input name="image" type="file" id="image">

Javascript

使用Javascript

data = new FormData();
    jQuery.each(jQuery('#image')[0].files, function(i, file) {
        data.append('image', file);
    });

$.ajax({
    url: "submit/ajax",
    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    data: data,
    success: function(response)
       {
          // Display your uploaded image on the page
       }
    });

PHP

PHP

Image::make($_FILES['image']['tmp_name']) >save("$myImageDirectory/$newImagegName");

#1


6  

To upload files via AJAX you need to use XHR Level 2. The FormData class needs a HTMLFormElement in the constructor if you want to send its key-value.

要通过AJAX上传文件,您需要使用XHR Level 2.如果要发送其键值,FormData类在构造函数中需要HTMLFormElement。

You should use:

你应该使用:

new FormData( document.getElementById('imagesform') );

Also you could use with jQuery:

你也可以使用jQuery:

new FormData( $("#imagesform").get(0) )

Check my answer in another similar question to get more information.

在另一个类似问题中查看我的答案以获取更多信息。

UPDATE: Seeing your comments your problem is with the Laravel route too. If the error code is 500 and it is showing the message "Method not allowed" you need to check your routes in routes/web.php. Please put here the stacktrace of the error and your route file (use pastebin or similar).

更新:看到你的评论你的问题也在于Laravel路线。如果错误代码为500并且显示消息“Method not allowed”,则需要检查routes / web.php中的路由。请在此处输入错误的堆栈跟踪和路由文件(使用pastebin或类似文件)。

#2


3  

I was able to solve a similar problem by Frankensteining various suggestions from here. That link has a pile of really good information. You need to assign some options in the ajax call to false. In any case this is what worked for me:

我能够通过Frankensteining来解决类似的问题。那个链接有很多非常好的信息。您需要将ajax调用中的一些选项指定为false。无论如何,这对我有用:

HTML

HTML

<input name="image" type="file" id="image">

Javascript

使用Javascript

data = new FormData();
    jQuery.each(jQuery('#image')[0].files, function(i, file) {
        data.append('image', file);
    });

$.ajax({
    url: "submit/ajax",
    type: 'POST',
    cache: false,
    contentType: false,
    processData: false,
    data: data,
    success: function(response)
       {
          // Display your uploaded image on the page
       }
    });

PHP

PHP

Image::make($_FILES['image']['tmp_name']) >save("$myImageDirectory/$newImagegName");