如何在 Laravel 中发送带有文件和数据数组的 PUT 请求
How to send PUT request with a file and an array of data in Laravel
我正在使用 Laravel 作为 API 并使用 Angularjs 作为前端来编写网络应用程序。我有一个使用 PUT 方法更新产品的表单,其中包含一系列信息和一个文件作为产品图像。但是我无法在控制器中获取输入请求,它是空的。
请看下面的代码:
web.php(路线)
Route::group(['prefix' => 'api'], function()
{
Route::put('products/{id}', 'ProductController@update');
});
我的angularjs产品服务:
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);
}
);
}
我的ProductController更新函数
public function update(Request $request, $id) {
// Just print the request data
dd($request->all());
}
这是我在 Chrome 检查员中看到的
请分享您对此问题的经验。谢谢。
试试这个方法:
public update(Request $request, $id)
{
$request->someVar;
$request->file('someFile');
// Get variables into an array.
$array = $request->all();
此外,请确保您使用 Route::put
或 Route::resource
作为路线。
根据 this discussion. What you should do instead is to 'fake' the PUT request by using Form Method Spoofing
,你不能那样做
你需要的只是正常的 POST 请求,新字段名为 _method=put 然后你的代码将正常工作:
我正在使用 Laravel 作为 API 并使用 Angularjs 作为前端来编写网络应用程序。我有一个使用 PUT 方法更新产品的表单,其中包含一系列信息和一个文件作为产品图像。但是我无法在控制器中获取输入请求,它是空的。
请看下面的代码:
web.php(路线)
Route::group(['prefix' => 'api'], function()
{
Route::put('products/{id}', 'ProductController@update');
});
我的angularjs产品服务:
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);
}
);
}
我的ProductController更新函数
public function update(Request $request, $id) {
// Just print the request data
dd($request->all());
}
这是我在 Chrome 检查员中看到的
请分享您对此问题的经验。谢谢。
试试这个方法:
public update(Request $request, $id)
{
$request->someVar;
$request->file('someFile');
// Get variables into an array.
$array = $request->all();
此外,请确保您使用 Route::put
或 Route::resource
作为路线。
根据 this discussion. What you should do instead is to 'fake' the PUT request by using Form Method Spoofing
,你不能那样做你需要的只是正常的 POST 请求,新字段名为 _method=put 然后你的代码将正常工作: