accessing files from upload module
ultimike - April 25, 2006 - 16:22
Hello,
I'm about to start writing a module that reads and parses in XML data from an uploaded file, then saves certain data from the XML file into a DB table.
I have all the pieces I need except for how I'm going to interact with the upload module when the node is created and the file is uploaded. Are there any hooks that I can use to access the uploaded file or is it best to use hook_insert, look up the filename, and open it from there?
What is the best way to go about this?
Thanks,
-mike

This should get you started with uploading a file
I recently wrote a module that upload a CSV file and wrote the data to several tables. The following snippet is based on that code and shows the three functions I used to do this; example_import (displays the form), example_import_validate (makes sure the file is valid and if so saves the fileinfo) and example_import_submit (opens the file and processes it - incomplete in the example.
<?php
function example_import() {
$form = array();
// Set the encoding type so file inputs work
$form['#attributes'] = array("enctype" => "multipart/form-data");
$form['filename'] = array('#type' => 'file', '#title' => t('File to import'), '#description' => t('Click "Browse..." to select a file to import.'));
// A place to put the file information if a valid file is supplied
// Set by example_import_validate
$form['fileinfo'] = array('#type' => 'value', '#value' => NULL);
$form['note'] = array('#type' => 'markup', '#title' => t('Please note'),
'#value' => '<div>' . t("Please only click 'submit' once - Importing may take a moment") . '<div>');
$form['buttons']['submit'] = array('#type' => 'submit', '#value' => t('Import data'));
$output .= drupal_get_form('example_import', $form);
return $output;
}
function example_import_validate($form_id, $form_values) {
$upload = file_check_upload('filename');
if ( $upload === FALSE ) {
form_set_error('filename', t('You must specify a file for importing.'));
}
else if ( $upload->filemime != 'text/plain' ) {
form_set_error('filename', t('Filename does not exist or is of wrong type'));
}
else {
$form_values['fileinfo']['#ref'] = $upload;
}
}
function example_import_submit($form_id, $form_values) {
$fileinfo = $form_values['fileinfo']['#ref'];
$record_count = 0;
$filepath = $fileinfo->filepath;
// Open the file
$handle = @fopen($filepath, "r");
if ($handle) {
// Read and process the file here
}
}
?>
what about the upload module
Nevets,
Thanks for the quick response - your code looks good, but I'm hoping to use the upload module and all of its ajaxy goodness. Is this not possible?
Once a file is uploaded using the upload module and the node is saved, is the filename accessible via the $node array ($node->filename???). If so, then I can access it that way and do my processing then. Make sense?
Thanks,
-mike