Upload an Image file to the server using Angular and PHP

In this post we will see how to upload an image file to the server using angular and PHP. Use this below code in your component.html file.

Html code:

<input style="display: none" type="file" (change)=" fileupload($event)" #selectFile>

<button (click)="selectFile.click()">Select File</button>

<button (click)="uploadfile()">Upload</button>

The above code is used to upload the file from the system.

This below code is used get the file from html code and append the file into form data and send to the server.

TS code:

selecetdFile : File;

fileupload (event)

{

this.selecetdFile = <File>event.target.files[0];

}

uploadfile ()

{

const imagedata = new FormData();

imagedata.append('image', this.selecetdFile, this.selecetdFile.name);

var url = “http://localhost/xxxxxxx/backend/uploadimg.php”; // your php file to get the image file

this.http.post(url, imagedata)
// you can create and use service here

.subscribe((data) => { Console.log(data)

},(error) =>

{

console.log(error);

});

}

PHP code:

Using PHP code we will receive the file from form data and upload into the below folder.

<?php

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS, FILES');

header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

$uploaadurl = "C:/wamp/www/xxxxxxx/backend/upload/"; // Folder path to upload

imageif(isset($_FILES['image'])){ $errors= array();

$file_name = $_FILES['image']['name'];

$file_size =$_FILES['image']['size'];

$file_tmp =$_FILES['image']['tmp_name'];

$file_type=$_FILES['image']['type'];

$file_ext=strtolower(end(explode('.',$_FILES['image']['name'])));

$expensions= array("jpeg","jpg","png");

if(in_array($file_ext,$expensions)=== false){

$errors[]="extension not allowed, please choose a JPEG or PNG file.";

}

if($file_size > 2097152){

$errors[]='File size must be excately 2 MB';

}

if(empty($errors)==true){

move_uploaded_file($file_tmp, $uploaadurl.$file_name);

echo “Successfully uploaded”;

}

else

{

print_r($errors);

}}?>

If your image file is not uploaded and then check your folder path may in live serve we need to give like

/home/xxxxxxx/folderpath/.

Thank you for reading this post. If you like this post share with your friends .

Leave a Reply

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

Subscribe For Latest Updates

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

Sutrula Thalangal will use the information you provide on this form to be in touch with you and to provide updates and marketing.