Posts Tagged file upload
Upload image using hidden iFrame (Simple Photo Manager)
Posted by admin in HTML, JavaScript, PHP on May 1st, 2009
You can view the working demo here.
You can download the source code here.
In this example we are using a hidden IFrame for uploading file without refreshing page.
Include IFRAME in your page.
<div id="iframe_container"> <iframe src="pm-upload.php" frameborder="0" style="height:75px;"></iframe> </div>
The pm-upload.php has a FROM with file input field. When user select a file for upload we have called a upload() function on onChange event of file element.
<form name="iform" action="" method="post" enctype="multipart/form-data"> <input id="file" type="file" name="image" onChange="window.parent.upload(this);" /><br> <span style="font-size:11px; color:#666666;">only gif, png, jpg files.</span> <input type="hidden" value="" name="div_id" /> </form>
If file successfully upload and satisfy all validation conditions then we call setUploadedImage() function to setup the information of recently uploaded file on parent window. we can access the parent window javascript functions like this:
window.parent.setUploadedImage();
If there is some validation error then we call uploadError() function of parent window.
Here is complete javascript code for this tutorial:
//Call at the time of upload function upload(fileObj){ var par = window.document; var frm = fileObj.form; var div_id = parseInt(Math.random() * 100000); // hide old iframe var iframes = par.getElementsByTagName('iframe'); var iframe = iframes[iframes.length - 1]; iframe.className = 'hidden'; // create new iframe var new_iframe = par.createElement('iframe'); new_iframe.src = 'pm-upload.php'; new_iframe.frameBorder = '0'; new_iframe.style.height = '75px'; par.getElementById('iframe_container').appendChild(new_iframe); // add image progress var images = par.getElementById('images_container'); var new_div = par.createElement('div'); new_div.id = div_id; var new_img = par.createElement('img'); new_img.src = 'images/indicator2.gif'; new_img.style.marginLeft = '33px'; new_img.style.marginTop = '50px'; new_div.appendChild(new_img); images.appendChild(new_div); var errorDiv = par.getElementById('error'); errorDiv.innerHTML = ""; errorDiv.style.display = 'none'; // send frm.div_id.value = div_id; setTimeout(frm.submit(),5000); } //Call when upload completed function setUploadedImage(imgSrc, fileTempName, divId) { var par = window.document; var images = par.getElementById('images_container'); var imgdiv = par.getElementById(divId); var image = imgdiv.getElementsByTagName('img')[0]; imgdiv.removeChild(image); var image_new = par.createElement('img'); image_new.src = imgSrc; image_new.className = 'pic'; var image_label = par.createElement('input'); image_label.type = "text"; image_label.maxLength = "40"; image_label.size = "12"; image_label.value = "Label"; image_label.name = "title[]"; var image_hidden = par.createElement('input'); image_hidden.type = "hidden"; image_hidden.value = "1"; image_hidden.name = "delFlag[]"; var image_name = par.createElement('input'); image_name.type = "hidden"; image_name.value = fileTempName + ",new"; image_name.name = "imageName[]"; var image_del_link = par.createElement('a'); image_del_link.href = "javascript:void(0)"; image_del_link.appendChild(par.createTextNode("Delete")); var br = par.createElement('br'); imgdiv.appendChild(image_new); imgdiv.appendChild(image_label); imgdiv.appendChild(image_hidden); imgdiv.appendChild(image_name); imgdiv.appendChild(br); imgdiv.appendChild(image_del_link); image_label.onfocus = function() { eval(labelOnFocus(image_label)); } image_label.onblur = function() { eval(labelOnBlur(image_label)); } image_del_link.onclick = function() { eval(deleteLinkOnClick(image_del_link, '')); } } // call when error occurred at the time of upload function uploadError(divId, oName) { var par = window.document; var images = par.getElementById('images_container'); var imgdiv = par.getElementById(divId); images.removeChild(imgdiv); var errorDiv = par.getElementById('error'); errorDiv.innerHTML = oName + " has invalid file type."; errorDiv.style.display = ''; } function labelOnFocus(image_label) { if (image_label.value == "Label") { image_label.value = ""; } } function labelOnBlur(image_label) { if (image_label.value == "") { image_label.value = "Label"; } } function deleteLinkOnClick(delLink, delFlag) { var par = window.document; var imgDiv = delLink.parentNode; var image_hidden = delFlag == '' ? imgDiv.childNodes[2] : par.getElementById(delFlag); if (image_hidden.value == '1') { image_hidden.value = '0'; delLink.removeChild(delLink.childNodes[0]); delLink.appendChild(par.createTextNode("Restore")); delLink.style.color = '#FF0000'; } else { image_hidden.value = '1'; delLink.removeChild(delLink.childNodes[0]); delLink.appendChild(par.createTextNode("Delete")); delLink.style.color = '#64B004'; } }
You can check the live demo of this tutorial and you can also download the source code of the sample demo. The demo example is very simple and only for learning purpose. You can easily extent the sample code as per your requirement.
Create image upload field using Drupal Form API
Posted by anil in Drupal, Open Source on April 28th, 2009

Product Form with Image Field
We can create a image/file upload field using Drupal Form API. Here I am considering an example of product form so we can easily understand its use and its implementation. Our product form have two fields product name and product image. I am considering only three fields productid, product name and product image in our product table. The productid is primary key and set to auto increment. Our module name is ‘product.module’.
STEP 1.
function new_product_form() { $form['product_name'] = array( '#title' => t('Product Name'), '#type' => 'textfield', '#required' => TRUE, '#description' => t('Please enter product name.'), ); // Product picture $form['picture'] = array('#type' => 'fieldset', '#title' => t('Product image')); $form['picture']['picture_upload'] = array('#type' => 'file', '#title' => t('Upload product image'), '#size' => 48, '#description' => t('Maximum dimensions are %dimensions and the maximum size is %size kB.', array('%dimensions' => '250x250', '%size' => '30'))); $form['#validate'][] = 'product_validate_picture'; $form['submit'] = array( '#type' => 'submit', '#value' => t('Submit'), ); $form['#redirect'] = 'product_list'; $form['#attributes']['enctype'] = 'multipart/form-data'; return $form; }
We have set the enctype of form as multipart/form-data because we are uploading the file. We also set a validation function product_validate_picture() for validating our uploaded image.
STEP 2.
Now we are creating product_validate_picture() function.
function product_validate_picture(&$form, &$form_state) { $validators = array( 'file_validate_is_image' => array(), 'file_validate_image_resolution' => array('250x250')), 'file_validate_size' => array(30 * 1024), ); if ($file = file_save_upload('picture_upload', $validators)) { // Remove the old picture. if (isset($form_state['values']['_product']->image_path) && file_exists($form_state['values']['_product']->image_path)){ file_delete($form_state['values']['_product']->image_path); } $productid = 0; if (!isset($form_state['values']['productid'])) { // Execute in case of new product $query = "SHOW TABLE STATUS LIKE 'product'"; $rs = db_query($query); $row = db_fetch_object($rs); $productid = isset($row->Auto_increment) ? $row->Auto_increment : 0; } else { $productid = $form_state['values']['productid']; } $info = image_get_info($file->filepath); $destination = variable_get('product_picture_path', 'product_pictures') .'/picture-'. $productid .'.'. $info['extension']; if (file_copy($file, $destination, FILE_EXISTS_REPLACE)) { $form_state['values']['picture'] = $file->filepath; } else { form_set_error('picture_upload', t("Failed to upload the picture image; the %directory directory doesn't exist or is not writable.", array('%directory' => variable_get('product_picture_path', 'product_pictures')))); } } }
Drupal provide a function file_save_upload() for saving the uploaded file to a new location. Its also take associative array of callback functions used to validate the file as optional argument. Here we passing three callback functions file_validate_is_image, file_validate_image_resolution, and file_validate_size for validating file type as image, image resolution and file size respectively. This function return an object containing the file information or 0 in case of error.
We are using this product_validate_picture() function in both new product and edit product form. So, if ‘_product’ is not set in form values then its fetch the id of next auto_increment value set in product table. In case of edit product form it replace the old product image with new image if user uploaded a new image.
We assign the uploaded image path in our form values so we can store that path in out product table.
$form_state['values']['picture'] = $file->filepath;
STEP 3.
function new_product_form_submit($form_id, $form) { $form_values = $form['values']; $product_name = trim($form_values['product_name']); $image_path = $form_values['picture']; $query = "INSERT INTO product(product_name, image_path) VALUES('%s', '%s')"; db_query($query, $product_name, $image_path); drupal_set_message(t('Product has been added successfully.')); }
Then we will save the product imformation in out product table.
STEP 4.
In case of edit product form we are passing productid as arg(2). We fetch the product imformation using this productid and set the default values in form. We also save the product information and productid in form values.
function edit_product_form() { $productid = arg(2); $query = "SELECT * FROM {product} WHERE productid = '%d'"; $rs = db_query($query, $productid); $product_data = db_fetch_object($rs); $form['_product'] = array('#type' => 'value', '#value' => $product_data); $form['productid'] = array('#type' => 'value', '#value' => $product_data->productid); $form['product_name'] = array( '#title' => t('Product Name'), '#type' => 'textfield', '#default_value' => stripslashes($product_data->product_name), '#required' => TRUE, '#description' => t('Please enter product name.'), ); // Product picture $form['picture'] = array('#type' => 'fieldset', '#title' => t('Product image')); $picture = theme('product_picture', (object)$product_data); if ($product_data->image_path) { $form['picture']['current_picture'] = array('#value' => $picture); $form['picture']['picture_delete'] = array('#type' => 'checkbox', '#title' => t('Delete picture'), '#description' => t('Check this box to delete your current picture.')); } else { $form['picture']['picture_delete'] = array('#type' => 'hidden'); } $form['picture']['picture_upload'] = array('#type' => 'file', '#title' => t('Upload product image'), '#size' => 48, '#description' => t('Maximum dimensions are %dimensions and the maximum size is %size kB.', array('%dimensions' => '250x250', '%size' => '30'))); $form['#validate'][] = 'product_validate_picture'; $form['#redirect'] = 'product_list'; $form['#attributes']['enctype'] = 'multipart/form-data'; return $form; }
STEP 5.
Then we will update the product detail. If user want to delete product image then we will delete the current image of product.
function edit_product_form_submit($form_id, $form) { $form_values = $form['values']; $product_name = trim($form_values['product_name']); $image_path = $form_values['_product']->image_path; // Delete picture if requested, and if no replacement picture was given. if (!empty($form_values['picture_delete']) && $form_values['picture'] == '') { if ($form_values['_product']->image_path && file_exists($form_values['_product']->image_path)) { file_delete($form_values['_product']->image_path); } $image_path = ''; } if (isset($form_values['picture']) && $form_values['picture'] != '') { $image_path = $form_values['picture']; } $query = "UPDATE {product} SET product_name = '%s', image_path = '%s' WHERE productid = '%d'"; db_query($query, $product_name, $image_path, $productid); drupal_set_message(t('Product has been updated successfully.')); }
STEP 6.
We are also theming our product image. For this, we are using a product-picture.tpl.php file. First we register our theme in theme registry using hook_theme() callback function.
function product_theme() { return array( 'product_picture' => array( 'arguments' => array('product' => NULL), 'template' => 'product-picture', ), ); } function template_preprocess_product_picture(&$variables) { $variables['picture'] = ''; $product = $variables['product']; if (!empty($product->image_path) && file_exists($product->image_path)) { $picture = file_create_url($product->image_path); } else if (variable_get('product_picture_default', '')) { $picture = variable_get('product_picture_default', ''); } if (isset($picture)) { $alt = t("@product's picture", array('@product' => $product->product_name )); $variables['picture'] = theme('image', $picture, $alt, $alt, '', FALSE); } }
<?php //product-picture.tpl.php file ?> <div class="picture"> <?php print $picture; ?> </div>
How upload file using cURL?
Here I am giving an example of how you can upload file using cURL in PHP.
Code:
<?php $request_url = ‘http://www.akchauhan.com/test.php’; $post_params['name'] = urlencode(’Test User’); $post_params['file'] = ‘@’.'demo/testfile.txt’; $post_params['submit'] = urlencode(’submit’); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $request_url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_params); $result = curl_exec($ch); curl_close($ch); ?>
Here we have first initialized the new CURL session using “curl_init” function. Then we have set few curl options for CURL session.
CURLOPT_URL: URL to fetch.
CURLOPT_POST: TRUE to regular HTML POST.
CURLOPT_RETURNTRANSFER: TRUE to return the transfer as a string of the return value of “curl_exec” instead of outputting it out directly.
CURLOPT_POSTFIELDS: The full data to post in a HTTP “POST” operation.
You can also set more options as per your requirement but these are the minimum require options for file upload. You can find more information about these options in PHP manual.
Then execute the CURL session through “curl_exec” function. This function will return the output of request.
Here the tricky part is ‘@’ symbol before file name. CURL automatically upload the give file to server or requested URL when it find the ‘@’ symbol in starting of file name.
Note: If you try this code on localhost under windows operating system then you might get the error message “CURL is failed to created the post data”. But this code is work fine under Linux environment. So, try this on your server.
The requested file “test.php” consider this request as simple POST FROM request. Like if you use this form for request.
<form method=”post” action=”test.php” enctype=”multipart/form-data”> <input type=”text” name=”name” value=”Test User” /> <input type=”file” name=”file” /> <input type=”submit” name=”submit” value=”submit” /> </form>
