How to show image in Angular 4 application read through laravel 5 rest api

Home / Uncategorized / How to show image in Angular 4 application read through laravel 5 rest api

Question:
I am using Angular 4 frontend and Laravel 5 Rest API for my application. I save and read images in Laravel using below code
public function store(Request $request) {

$file = $request->file(‘filefield’);
$extension = $file->getClientOriginalExtension();
Storage::disk(‘local’)->put($file->getFilename().’.’.$extension, File::get($file));
$entry = new Image();
$entry->mime = $file->getClientMimeType();
$entry->original_filename = $file->getClientOriginalName();
$entry->filename = $file->getFilename().’.’.$extension;

$entry->save();

return response()->success([‘image’ => $entry]);

}

public function get(Image $image){

$file = Storage::disk(‘local’)->get($image->filename);

return (new Response($file, 200))
->header(‘Content-Type’, $image->mime);
}

This works fine. I am able to post and save image using Angular frontend. I am able to retrieve and see image using just the API i.e. if I open the URL myapplication/api/images/1 in the browser, I see the image.

But I am having issue retrieving and showing image using Angular Here are the Angular code excerpts for the service, component
getImage(id: number): Promise {
return this._http.get(this.imageUrl + id)
.toPromise()
.then(response => response as any)
.catch(this.handleError);
}

This calls the correct URL e.g. http://myapplication/api/images/1

Service is called here in the component (hard coded image id just to test)
this.route.paramMap
.switchMap((params: ParamMap) => this.packageService.getImage(1))
.subscribe(image => this.image = image);

and this is the component HTML:

But I get this error
unsafe:Response with status: 200 OK

How can I resolve this error and show the image in Angular 4 application received through Laravel REST API.


Answer:

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *