file upload code example

Example 1: php upload file

<?php
   if(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'])));
      
      $extensions= array("jpeg","jpg","png");
      
      if(in_array($file_ext,$extensions)=== 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,"images/".$file_name);
         echo "Success";
      }else{
         print_r($errors);
      }
   }
?>

Example 2: basic code for file upload in php

//This is the minimal code for an image upload for first time learners
//html portion
<!DOCTYPE html>
<html>
<head>
	<title>ImageUpload</title>
</head>
<body>
	<form action="upload.php" method="post" enctype="multipart/form-data">
		<label>Username</label>
		<input type="text" name="username">
		<br>
		<label>UploadImage</label>
		<input type="file" name='myfile'>
		<br/>
		<input type="submit" value="upload">
	</form>
</body>
</html>
  
 //php portion
  <?php
	$user=$_POST['username'];
	$image=$_FILES['myfile'];
	echo "Hello $user <br/>";
	echo "File Name<b>::</b> ".$image['name'];

	move_uploaded_file($image['tmp_name'],"photos/".$image['name']);
	//here the "photos" folder is in same folder as the upload.php, 
	//otherwise complete url has to be mentioned
	?>

Example 3: file upload

uploadFile(e){
    const file = e.target.files[0];
    storage.ref('images/'+ file.name).put(file)
      .then(response => {
        response.ref.getDownloadURL().then((downloadURL) => {
           firebase.database().ref(YOUR_DATABASE).child(THE_USER_ID).update({imageUrl:downloadURL})
      }                 
     .catch(err => console.log(err))
}

Example 4: file uploading

const express = require('express');
const authenticate = require('../authenticate');
const multer = require('multer');

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'public/images');
    },
    filename: (req, file, cb) => {
        cb(null, file.originalname)
    }
});

const imageFileFilter = (req, file, cb) => {
    if(!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
        return cb(new Error('You can upload only image files!'), false);
    }
    cb(null, true);
};

const upload = multer({ storage: storage, fileFilter: imageFileFilter});

const uploadRouter = express.Router();

uploadRouter.route('/')
.get(authenticate.verifyUser, authenticate.verifyAdmin, (req, res) => {
    res.statusCode = 403;
    res.end('GET operation not supported on /imageUpload');
})
.post(authenticate.verifyUser, authenticate.verifyAdmin, upload.single('imageFile'), (req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.json(req.file);
})
.put(authenticate.verifyUser, authenticate.verifyAdmin, (req, res) => {
    res.statusCode = 403;
    res.end('PUT operation not supported on /imageUpload');
})
.delete(authenticate.verifyUser, authenticate.verifyAdmin, (req, res) => {
    res.statusCode = 403;
    res.end('DELETE operation not supported on /imageUpload');
});

module.exports = uploadRouter;

Example 5: php upload

// To change: FILENAME, array with allowed extensions, Max Filesite, Filepath
if(upload("FILENAME", array("jpeg","jpg","png"), 209715, "C:/xampp/htdocs/")){
        echo "Success";
    }


function upload($f_name, $f_ext_allowed, $f_maxsize, $f_path){

      $f_name_2 = $_FILES[$f_name]['name'];
      $f_size  =  $_FILES[$f_name]['size'];
      $f_tmp   =  $_FILES[$f_name]['tmp_name'];
      $f_error =  $_FILES[$f_name]['error'];
      $f_ext   = strtolower(end(explode('.',$f_name_2)));
      $f_rename = $_SESSION['uid'] . "." . $f_ext;

        if($f_error == 0 && in_array($f_ext, $f_ext_allowed) 
        && $f_size < $f_maxsize && mb_strlen($f_name_2, "UTF-8") < 225 
        && preg_match("`^[-0-9A-Z_\.]+$`i", $f_name_2)){
            if(move_uploaded_file($f_tmp, $f_path . $f_name_2){
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
}

Example 6: how to upload

In order to upload file using selenium we need to locate the upload button 
in the DOM html. Then we do sendKeys by passing the path to the file. 

First, I locate the element which takes the path of the file(Choose file button) :
      WebElement input = driver.findElement(“id”); 
 And then I provide the path to the file using the sendKeys method :
      input.sendKeys(“/path/to/file” + Keys.ENTER);

Tags:

Css Example