Write data on a server
Click in the image or press the button to load a file from your disk space.
Select a JPG, PNG, GIF or SVG file. NOTE: The maximum size of the file is configured to 1 MB and the maximum width of the display to 320 px.
Open a folder containing images with the explorer of your file system. Drag and drop a JPG, PNG, GIF or SVG file over the image.
Edit the width or the height of the image.
Try the Undo and Redo buttons.
Reload the page. The modifications are saved.
For the code of the editor, consult the manual pages ImageSizeInspector and Editor and the article Architecture of an editor.
Click on the button to upload the image with its dimensions on the server.
The file is transferred in 100 kB blocks. The progression is displayed by a percentage. When the transfer is over, a check mark is displayed next to the button. An error is signaled by an exclamation point in red.
Code
The image is copied in the disk space of the server in response to a POST by a function which extracts from it the MIME type and the size of the file, the width and the height of the image, the block of data which is transferred, its size and its position in the file. A block of data is encoded in BASE64.
In iZend, the file uploadimage.php is installed directly in the folder actions. To activate the URL /uploadimage in a website, an entry is added in the file aliases.inc to the list of URLs common to all languages.
array(
'captcha' => 'captcha',
),
'en' => array(
);
Adapt the installation of this function to your development environment.
- define('TMP_DIR', ROOT_DIR . DIRECTORY_SEPARATOR . 'tmp');
- define('IMAGE_MAX_SIZE', 1000000);
Defines TMP_DIR
- the folder where the image file is saved - to the name of the subfolder tmp in the root folder of the site and IMAGE_MAX_SIZE
- the maximum size of an image - to 1 MB.
- function uploadimage($lang, $arglist=false) {
Defines the function uploadimage
which is called by the URL /uploadimage of the site.
The arguments $lang
- the language of the output, which will always be false
- and $arglist
- the parameters passed in the URL - are not used.
- $maxfilesize=IMAGE_MAX_SIZE;
- $filetypes=array('image/jpeg', 'image/png', 'image/gif', 'image/svg+xml');
Initializes $maxfilesize
to IMAGE_MAX_SIZE
and $filetypes
to the list of supported MIME types.
- $type=$data=false;
- $size=$offset=0;
- $width=$height=0;
Initializes the variables of the arguments of the POST.
- if (isset($_POST['file_size'])) {
- $size=$_POST['file_size'];
- }
- if (isset($_POST['file_type'])) {
- $type=$_POST['file_type'];
- }
- if (isset($_POST['file_offset'])) {
- $offset=$_POST['file_offset'];
- }
- if (isset($_POST['file_data'])) {
- $data=base64_decode($_POST['file_data'], true);
- }
- if (isset($_POST['image_width'])) {
- $width=$_POST['image_width'];
- }
- if (isset($_POST['image_height'])) {
- $height=$_POST['image_height'];
- }
Extracts the arguments of the POST. The block of data encoded in BASE64 is decoded.
- if (($width = filter_var($width, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)))) === false)
- goto badrequest;
- if (($height = filter_var($height, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)))) === false)
- goto badrequest;
- if (($offset = filter_var($offset, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)))) === false)
- goto badrequest;
- if (($size = filter_var($size, FILTER_VALIDATE_INT, array('options' => array('min_range' => 0, 'max_range' => $maxfilesize)))) === false)
- goto badrequest;
- if (!$type or !in_array($type, $filetypes)) {
- goto badrequest;
- }
Checks the arguments of the POST.
- if (!$data) {
- goto badrequest;
- }
- $datasize=strlen($data);
- if ($offset + $datasize > $size) {
- goto badrequest;
- }
Checks the size of the data sent in the POST.
- goto trashfile;
On this server, writing the file is simulated. To check that the image has been copied properly by displaying it, comment out this instruction and adapt the rest of the code to save the file in a folder which is writable by the server.
- $name='image';
- switch ($type) {
- case 'image/jpeg':
- $fname = $name . '.jpg';
- break;
- case 'image/png':
- $fname = $name . '.png';
- break;
- case 'image/gif':
- $fname = $name . '.gif';
- break;
- case 'image/svg+xml':
- $fname = $name . '.svg';
- break;
- default:
- goto badrequest;
- }
- $file = TMP_DIR . DIRECTORY_SEPARATOR . $fname;
Defines the name of the image file. The extension of the file name depends on the MIME type of the image.
- $fout = @fopen($file, $offset == 0 ? 'wb' : 'cb');
- if ($fout === false) {
- goto internalerror;
- }
Opens the image file in binary mode. If the POST contains the first block of data, the file is created.
- $r = fseek($fout, $offset);
- if ($r == -1) {
- goto internalerror;
- }
Moves the file pointer to the position of the block of data.
- $r = fwrite($fout, $data);
- if ($r === false) {
- goto internalerror;
- }
Writes the block of data.
- if ($offset + $datasize < $size) {
- return false;
- }
Returns a plain header 200 Ok
if more blocks of data are expected.
- $file = TMP_DIR . DIRECTORY_SEPARATOR . $name . '.json';
- $data = array('width' => $width, 'height' => $height, 'name' => $fname);
- $r = @file_put_contents($file, json_encode($data));
- if ($r === false) {
- goto internalerror;
- }
- return false;
If all the image data is saved, creates a file image.json in the same directory giving the width and the height of the image and the name of the file. Returns a plain header 200 Ok
.
- trashfile:
- return false;
Returns a plain header 200 Ok
without saving the data.
- badrequest:
- header('HTTP/1.1 400 Bad Request');
- return false;
Returns a plain header 400 Bad Request
if an element of the POST is invalid.
- internalerror:
- header('HTTP/1.1 500 Internal Error');
- return false;
- }
Returns a plain header 500 Internal Error
if the image couldn't be saved properly.
- <?php $debug=false; ?>
Setting $debug
to true
gives access in the console of the navigator to all the components of the interface.
If $debug
is false
, all the code in JavaScript is protected by a closure function.
- <?php $filetypes=array('image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'); ?>
- <?php $maxsize=1000000; ?>
- <?php $imgname='image'; ?>
- <?php $imgsrc='/files/images/loadimage.png'; ?>
- <?php $imgwidth=320; ?>
- <?php $imgheight=180; ?>
- <?php $uploadurl='/uploadimage'; ?>
- <?php $chunksize=100000; ?>
Defines the MIME types supported by the editor, the maximum size of an image, the name of the storage item in the navigator, the URL of the initial image, the width and the height of the display of the image, the URL of the save function of the server, the size of the blocks of data sent to the server.
- <?php $id=uniqid('id'); ?>
Defines the identifier of the <div>
which surrounds the editor.
- #<?php echo $id; ?> .ojs img {
- max-width: <?php echo $imgwidth; ?>px;
- }
- #<?php echo $id; ?> #uploadstatus {
- font-size: smaller;
- }
Configures the width of the image display. Shows the progression of a transfer in a smaller font.
- <div id="<?php echo $id; ?>" class="noprint">
- <div class="ojs">
- <div>
- <div class="ojs_undo">
- <button type="submit" class="ojs_button narrow control_undo" disabled><i class="fas fa-undo"></i></button>
- <button type="submit" class="ojs_button narrow control_redo" disabled><i class="fas fa-redo"></i></button>
- </div>
- <span class="ojs_dimension">
- <input class="ojs_width" type="number" min="0"/> <i class="fas fa-arrows-alt-h small"></i>
- <input class="ojs_height" type="number" min="0"/> <i class="fas fa-arrows-alt-v small"></i>
- </span>
- </div>
- <div><img src="<?php echo $imgsrc; ?>" alt="" width="<?php echo $imgwidth; ?>" height="<?php echo $imgheight; ?>"/></div>
- <div>
- <span><button id="loadimage" type="submit" class="ojs_button narrow"><i class="fas fa-file-image"></i></button></span>
- <span><button id="uploadimage" type="submit" class="ojs_button narrow"><i class="fas fa-file-export"></i></button></span>
- <span id="uploadstatus"></span>
- </div>
- </div>
- </div>
Creates the widgets for the instances of UndoPanel and ImageSizeInspector, the container of the image and the buttons to load a local file and upload it on the server.
- <?php head('javascript', '/objectivejs/Objective.js'); ?>
- <?php head('javascript', '/objectivejs/Responder.js'); ?>
- <?php head('javascript', '/objectivejs/View.js'); ?>
- <?php head('javascript', '/objectivejs/Model.js'); ?>
- <?php head('javascript', '/objectivejs/Validator.js'); ?>
- <?php head('javascript', '/objectivejs/Editor.js'); ?>
- <?php head('javascript', '/objectivejs/Inspector.js'); ?>
- <?php head('javascript', '/objectivejs/NumberInspector.js'); ?>
- <?php head('javascript', '/objectivejs/DimensionInspector.js'); ?>
- <?php head('javascript', '/objectivejs/ImageInspector.js') ?>
- <?php head('javascript', '/objectivejs/SequenceInspector.js') ?>
- <?php head('javascript', '/objectivejs/ImageSizeInspector.js') ?>
- <?php head('javascript', '/objectivejs/ImageModel.js'); ?>
- <?php head('javascript', '/objectivejs/Undo.js'); ?>
- <?php head('javascript', '/objectivejs/Panel.js'); ?>
- <?php head('javascript', '/objectivejs/UndoPanel.js'); ?>
- <?php head('javascript', '/objectivejs/ModelStorageDelegate.js'); ?>
Includes the code of all the necessary classes.
REMINDER: The function head
of the iZend library adds a tag such as <script src="/objectivejs/Objective.js"></script>
to the <head>
section of the document in HTML.
Adapt the code to your development environment.
- function ImageLoader(model, inspectors, panel, upload, status) {
- Editor.call(this, model, null, inspectors, panel);
- if (upload)
- upload.onclick = () => this.upload();
- this._upload = upload;
- this._status = status;
- }
- ImageLoader.prototype = Object.create(Editor.prototype);
- Object.defineProperty(ImageLoader.prototype, 'constructor', { value: ImageLoader, enumerable: false, writable: true });
- ImageLoader.uploadURL = '/uploadimage';
- ImageLoader.chunkSize = 100000;
- ImageLoader.prototype.upload = function() {
- const {image} = this._model.get();
- if (image.image === null)
- return;
- const [url] = image.image;
- const [width, height] = image.size;
- const imgtype = /^data:(image\/[-.+0-9a-zA-Z]+);base64,/.exec(url)[1];
- const imgdata = atob(url.substring(url.indexOf(',')+1));
- const imgsize = imgdata.length;
- const uploadurl = ImageLoader.uploadURL;
- const chunksize = ImageLoader.chunkSize;
- let offset = 0;
- let progress = 0;
- const uploadslice = () => {
- if (this._status && imgsize > chunksize)
- this._status.innerText = `${progress}%`;
- const data = imgdata.substring(offset, offset + chunksize);
- $.post(uploadurl, {file_size: imgsize, file_type: imgtype, file_offset: offset, file_data: btoa(data), image_width: width, image_height: height })
- .done(() => {
- offset += data.length;
- progress = Math.floor((offset / imgsize) * 100);
- if (progress < 100)
- uploadslice();
- else {
- if (this._status)
- this._status.innerHTML = '<i class="fas fa-check-circle"></i>';
- if (this._upload)
- this._upload.disabled = false;
- }
- })
- .fail(() => {
- if (this._status)
- this._status.innerHTML = '<i class="fas fa-exclamation-circle inerror"></i>';
- if (this._upload)
- this._upload.disabled = false;
- });
- };
- if (this._status)
- this._status.innerText = '';
- if (this._upload && imgsize > chunksize)
- this._upload.disabled = true;
- uploadslice();
- }
An instance of ImageLoader is an Editor which can upload an image with a size on a server.
upload
gets the data of the model, extracts the type of the image and the image data in BASE64, computes its size, sends to the server all this information and the image data in 100 kB sequential blocks, displays the status of the operation.
- <?php if (!$debug): ?>
- (function() {
- <?php endif; ?>
Isolates all the code in JavaScript in a closure function if $debug
is false
.
- const model = new ImageModel('<?php echo $imgname; ?>');
- const container = document.querySelector('#<?php echo $id; ?>');
- const panel = new UndoPanel();
- panel.setManagedWidget(container.querySelector('.ojs_undo')).resetWidget();
- const filetypes = [<?php echo implode(',', array_map(function($s) { return "'$s'"; }, $filetypes)); ?>];
- const imageInspector = new ImageInspector(null, { filetypes: filetypes, maxsize: <?php echo $maxsize; ?> });
- imageInspector.setManagedWidget(container.querySelector('img'));
- const sizeInspector = new DimensionInspector(0, 0, {minWidth: 0, minHeight: 0});
- sizeInspector.setManagedWidget(container.querySelector('.ojs_dimension')).resetWidget();
- const imageSizeInspector = new ImageSizeInspector(imageInspector, sizeInspector);
- const loadimage = container.querySelector('#loadimage');
- loadimage.onclick = () => imageInspector.loadImage();
- const inspectors = {
- image: imageSizeInspector
- };
- const uploadimage = container.querySelector('#uploadimage');
- const uploadstatus = container.querySelector('#uploadstatus');
- const editor = new ImageLoader(model, inspectors, panel, uploadimage, uploadstatus);
- model.setDelegate(new ModelStorageDelegate());
- model.readIn();
- model.enableSync();
Creates the data model to be edited.
Retrieves the <div>
which surrounds the HTML of the program
Creates the panel with the buttons to undo and redo a modification, creates the inspector for the image and its size, creates the independent button which allows to load an image, creates the editor.
Associates the model to a delegate in charge of saving its data in the storage space of the navigator. Configures the model with the data already saved. Enables saving the data of the model whenever it is changed.
- <?php if (!$debug): ?>
- })();
- <?php endif; ?>
Closes the function which isolates the code in JavaScript if $debug
is false
.
SEE ALSO
ImageModel, ModelStorageDelegate, ImageSizeInspector, Editor, Wall, Architecture of an editor, Configure charts by Plotly
Comments