Upload Media to Your Site Using these 3 Programming Languages


Upload Media to Your Site Using these 3 Programming Languages


Websites today tend to use a large amount of media, such as images and video, to aid communication and improve the overall graphic impact. Many sites are also dynamic and interactive, allowing users to upload their own images and video. However, enabling lay users to modify or add to a website requires an easy-to-use, automated mechanism for upload.


A major consideration when using visual or audio-visual media is that it can be heavy, often taking up more than half the size of a webpage, especially if it is high-resolution. Large files slow down the uploading process, and you need to find a way to store them. There are numerous solutions for storing media files, including server-based and cloud-based storage.

You can store your files a Content Delivery Network (CDN), which distributes your data across multiple servers located around the world. CDNs are suitable for content-rich websites with heavy traffic and are often cloud-based. Cloud hosting is often preferred for its flexibility and scalability, and its ability to respond dynamically to the bandwidth of a user.

To help prevent a slow website that annoys customers, and to save bandwidth, you can optimize and compress media files. However, compression of large files can also be slow, so it may be more efficient to resize media files instead, resulting in a lower resolution. You need to find the right balance between the quality of an image or video and the size of the file. 

How to Upload an Image or Video Using PHP, Python, and AJAX


Below are three brief tutorials for uploading an image or video using these programming languages.

Uploading Videos with PHP

The following steps are a brief guide for uploading videos to a website. See the full tutorial.

1. Create an Upload form using HTML


<form action="" method='post' enctype="multipart/form-data">
<input type="file" name="file"/><br><br>
<input type="submit" value="Upload"/>
</form>
</form>

You can now insert PHP code to add functionality and enable the form to perform uploads.

2. Insert a Block of Code to Name the File and Extension


Use a temporary name ($tmp) for the duration of the upload. Establish a path to ensure the videos are actually uploaded and include the (isset($name)) function to confirm whether the submit button has been clicked. Specify actions for the user to complete, such as “Please choose a file”, and output statements based on boolean logic.

<?php

$name= $_FILES['file']['name'];
$tmp_name= $_FILES['file']['tmp_name'];
$position= strpos($name, ".");
$fileextension= substr($name, $position + 1);
$fileextension= strtolower($fileextension);
if (isset($name)) {
$path= 'Uploads/videos/';
if (empty($name))
{
echo "Please choose a file";
}
else if (!empty($name)){
if (($fileextension !== "mp4") && ($fileextension !== "ogg") && ($fileextension !== "webm"))
{
echo "The file extension must be .mp4, .ogg, or .webm in order to be uploaded";
}

else if (($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm"))
{
if (move_uploaded_file($tmp_name, $path.$name)) {
echo 'Uploaded!';
}
}
}
}
?>

3. Now add the Second Block of PHP Code to Specify Which File Types will be Shown

<?php
if (($fileextension == "mp4") || ($fileextension == "ogg") || ($fileextension == "webm"))
{
echo "<video width='320' controls>
<source src='$path/$name' type='video/$fileextension'>
Your browser does not support the video tag.
</video>";
}
?>

4. If You Wants to Restrict the Size of Your File, Write the First Code Block as

<?php

$name= $_FILES['file']['name'];
$tmp_name= $_FILES['file']['tmp_name'];
$size= $_FILES['file']['size'];
$path= "Uploads/Files/";
if (isset($name)) {
if (empty($name))
{
echo "Please choose a file";
}
else if ((!empty($name)) && ($size < 20971520))
{
move_uploaded_file($tmp_name, $path . $name);
echo 'Uploaded!';
}
else
{
echo "The size of the file must be less than 20MB in order to be uploaded.";

}
}
?>
The second block will look like this


<?php
if (!empty($tmp_name)){
echo "The file you uploaded is shown below.<br><br>";
echo "<a href='$path" ."$name'>$name</a>";
}
?>

Uploading Images with Python


The following steps are for uploading images in Django, using ImageField. See the full tutorial.


1. In the settings.py file, add the following code


MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

2. Edit the Configuration in the urls.py as so

if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)

3. Create a Model of an Object, Including a Name and Image

In this example, we use a hotel model:

# models.py
class Hotel(models.Model):
name = models.CharField(max_length=50)
hotel_Main_Img = models.ImageField(upload_to='images/')

Django automatically creates a media directory when you upload an image, while upload_to specifies the location of the image.

4. Under image_app, Create a forms.py file

# forms.py
from django import forms
from .models import *
class HotelForm(forms.ModelForm):
class Meta:
model = Hotel
fields = ['name', 'hotel_Main_Img']

5. Next, We Have to Create an HTML File for Uploading Images

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hotel_image</title>
</head>
<body>
<form method = "post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Upload</button>
</form>
</body>
</html>

6. Create a View to Access the Images

# Python program to view

# for displaying images

def display_hotel_images(request):

if request.method == 'GET':

# getting all the objects of hotel.
Hotels = Hotel.objects.all()

return render((request, 'display_hotel_images.html',
{'hotel_images' : Hotels}))

7. To Finalize the Upload, Create a URL Path

# urls.py
path('hotel_images', display_hotel_images, name = 'hotel_images')

Upload an Image with AJAX


This example focuses on uploading images using standard HTML. See the full tutorial, or check out automated tools for ajax file upload

1. Create an Image Preview Area

<div id="upload-area">
<div id="preview">
<img width="100px" height="100px" src="/images/icons/128px/zurb.png" id="thumb">
</div>
<form action="/playground/ajax_upload" id="newHotnessForm">
<label>Upload a Picture of Yourself</label>
<input type="file" size="20" id="imageUpload" class=" ">
<button class="button" type="submit">Save</button>
</form>
</div>

2. Attach jQuery and the AJAX Upload jQuery Plugin

<script src="/js/jquery.min.js" type="text/javascript"></script>
<script src="/js/ajaxupload.js" type="text/javascript"></script>
$(document).ready(function(){
var thumb = $('#thumb');
new AjaxUpload('imageUpload', {

3. Specify an Action URL

action: $('#newHotnessForm').attr('action'),
name: 'image',
onSubmit: function(file, extension) {

4. Add a “loading” Class to Hide the Image

$('#preview').addClass('loading');
},

5. Upon Completion, Delete the Loading Class

Set the image src to the response URL you receive from the plugin
onComplete: function(file, response) {
thumb.load(function(){
$('#preview').removeClass('loading');
thumb.unbind();
});
thumb.attr('src', response);
}
});
});

Conclusion

It’s important to automate and streamline the process of uploading media to your site. In this article, we showed how to enable users to upload images in three programming languages: PHP, Python, and AJAX. There are many additional considerations we did not take care of in these brief tutorials, such as image optimization, compression, and manipulation. We hope this will take you at least one step of the way to a media-rich website with active user participation.

Post a Comment Default Comments

Individuals who comment on FromDev at regular basis, will be rewarded in Top Commenter section. (Comments are selectively moderated so please do not spam)

emo-but-icon

...

item