How to send PUT request with a file and an array of data in Laravel

余生长醉 提交于 2020-04-09 18:07:48

问题


I am programing a web app using Laravel as API and Angularjs as frontend. I have a form to update product using PUT method with a array of informations and a file as product image. But I couldn't get the input requests in the controller, it was empty.

Please see the code below :

web.php ( route )

Route::group(['prefix' => 'api'], function()
{
    Route::put('products/{id}', 'ProductController@update');
});

My angularjs product service :

function update(productId, data, onSuccess, onError){
        var formData = new FormData();
        formData.append('imageFile', data.imageFile);
        formData.append('image', data.image);
        formData.append('name', data.name);
        formData.append('category_id', data.category_id);
        formData.append('price', data.price);
        formData.append('discount', data.discount);
        Restangular.one("/products", productId).withHttpConfig({transformRequest: angular.identity}).customPUT(formData, undefined, undefined,   {'Content-Type': undefined}).then(function(response) {

                onSuccess(response);

            }, function(response){

                onError(response);

            }
        );
    }

My ProductController update function

public function update(Request $request, $id) {
// Just print the request data
        dd($request->all());
    }

This is what I see in Chrome inspectmen

Please share your experiences on this problem. Thanks.


回答1:


what you need is Only normal POST request with new field named _method=put then your code will work normally:




回答2:


You can't do that, according to this discussion. What you should do instead is to 'fake' the PUT request by using Form Method Spoofing




回答3:


Try this method:

public update(Request $request, $id)
{
    $request->someVar;
    $request->file('someFile');

    // Get variables into an array.
    $array = $request->all();

Also, make sure you're using Route::put or Route::resource for your route.



来源:https://stackoverflow.com/questions/39942670/how-to-send-put-request-with-a-file-and-an-array-of-data-in-laravel

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!