我正在尝试从我的angularjs应用程序上传一个图像文件到我的API,它是用Laravel构建的,我的html页面看起来像这样:
<label for="">Import from file:</label>
<div class="row">
<div class="col-lg-12">
<input type="file" nv-file-select="" multiple="false" uploader="uploader"/>
<br><br>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div ng-repeat="item in uploader.queue">
<button type="button" class="btn btn-success btn-sm" ng-click="item.upload()"
ng-disabled="item.isReady || item.isUploading || item.isSuccess">
<span class="glyphicon glyphicon-upload"></span> Upload
</button>
<br><br>
</div>
{{uploadStatus}}
</div>
</div>
在我的控制器中,我有以下代码:
var uploader = $scope.uploader = new FileUploader({
url: REST_END_POINT + 'businesses/158',
method: 'PUT',
headers: {
Authorization: 'Bearer ' + localStorage.getItem('satellizer_token')
},
formData: []
});
现在我的Api函数是这样的:
$file = $request->file('file');
if ($file) {
return response()->json('file exists');
try {
Storage::put('/teams/businesses/logo/' . $business->team_id . '/' . $file->getClientOriginalName(), File::get($file));
$business->logo = $file->getClientOriginalName();
} catch (\Exception $e) {
return response()->json(['Something went wrong while uploading the file' => 'Error', 'success' => false, 'status' => 500, 'data' => $e]);
}
}else{
return response()->json('file !exists');
}
因此,当我尝试从Angularjs应用程序提交时,它会打印“文件!exists”。所以这个文件不存在,我不知道为什么。
api路由器如下所示:
Route::put('businesses/{id}', ['as' => 'update_business', 'uses' => 'BusinessController@update']);
你知道这段代码出了什么问题吗?
发布于 2016-01-14 23:51:04
在你的php代码中,在你尝试存储文件之前,你正在return
一个响应。return
语句会暂停脚本的执行。
$file = $request->file('file');
if ($file) {
return response()->json('file exists'); // execution stops here
// might as well comment all of this out...it will never execute
//try {
// Storage::put('/teams/businesses/logo/' . $business->team_id . '/' . $file->getClientOriginalName(), File::get($file));
// $business->logo = $file->getClientOriginalName();
//} catch (\Exception $e) {
// return response()->json(['Something went wrong while uploading the file' => 'Error', 'success' => false, 'status' => 500, 'data' => $e]);
//}
}else{
return response()->json('file !exists');
}
你想要做一些更多的事情,就像这样:
// Don't overwrite the file if it already exists
if ($file = $request->file('file')) {
return response()->json('file exists');
}
// File does not exist. Go ahead and attempt to save it.
try {
Storage::put('/teams/businesses/logo/' . $business->team_id . '/' . $file->getClientOriginalName(), File::get($file));
$business->logo = $file->getClientOriginalName();
} catch (\Exception $e) {
return response()->json(['Something went wrong while uploading the file' => 'Error', 'success' => false, 'status' => 500, 'data' => $e]);
}
return response()->json('file uploaded successfully');
https://stackoverflow.com/questions/34796942
复制相似问题