I am trying to loop through an array of photos and add them during node creation. I am parsing an XML document and creating a node object manually then using node_save to create it. I have tried following examples, and came to this:

										
					foreach ($photos as $photo) {
						// create a file name and save it in a tmp directory
						// file_get_contents() upload tmp photo
						
						$image = file_save_data($photo['Data'], NULL, $replace = FILE_EXISTS_RENAME);
						
						if ($image != 0) {
							// Load up the CCK field
							$field = content_fields('field_photo', 'house');
							
							// Load up the appropriate validators
							$validators = array_merge(filefield_widget_upload_validators($field), imagefield_widget_upload_validators($field));
							
							// Where do we store the files?
							$files_path = filefield_widget_file_path($field);
							
							// Create the file object, replace existing file with new file as source and dest are the same
							$file = field_file_save_file($image, $validators, $files_path, FILE_EXISTS_REPLACE);
							
							// Apply the file to the field, this sets the first file only, could be looped
							$node->field_photo[] = $file;
						} else {
							// error message log
							watchdog('test', 'Error during photo upload to temp directory.', array(), WATCHDOG_CRITICAL);
						}	
					}

It hits the watchdog error every time. What am I doing wrong? Am I missing code for this file upload portion?

Comments

kevinquillen’s picture

Forgot to mention I am using the latest stable version of CCK.

kevinquillen’s picture

Status: Active » Closed (fixed)

Got it.


$upload_directory = file_directory_path();
												
						if (file_check_directory($upload_directory, 1)) {
							$upload_destination = $upload_directory  . '/' . $listing . '-' . $number . '.jpg';
							
							$image_data = $photo['Data'];
													
							$image = file_save_data($image_data, $upload_destination, $replace = FILE_EXISTS_REPLACE);
							
							if ($image) {
								// Load up the CCK field
								$field = content_fields('field_photo', 'listing');
								
								// Load up the appropriate validators
								$validators = array_merge(filefield_widget_upload_validators($field), imagefield_widget_upload_validators($field));
								
								// Where do we save the file?
								$files_path = filefield_widget_file_path($field);
								
								// Create the file object, replace existing file with new file as source and dest are the same
								$file = field_file_save_file($image, $validators, $files_path, NULL);
								
								$node->field_photo[] = $file;
								
							} else {
								// error message log
								watchdog('rets', 'Error during photo upload to @dir directory.', array('@dir' => $upload_directory), WATCHDOG_CRITICAL);
							}	
						} else {
							watchdog('rets', 'Error creating @dir directory.', array('@dir' => $upload_directory), WATCHDOG_CRITICAL);
						}