我正在尝试将我的angularjs应用程序中的图像文件上传到我在Laravel中构建的API,我的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 App提交时,它会打印&#34; file!exists&#34;。所以文件不存在,我不知道为什么。
api路由器看起来像:
Route::put('businesses/{id}', ['as' => 'update_business', 'uses' => 'BusinessController@update']);
您是否知道此代码有什么问题?
答案 0 :(得分:0)
在您的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');