File field is showing that my previously uploaded files are 0 bytes

639 Views Asked by At

Got a bit of a weird issue here. I recently started doing maintenance on a website that I did not originally build. The Drupal site has a bunch of nodes with an audio file field, and a jQuery player that plays them. On a lot of the nodes the player does not load, and I've realized this is because the file is reported as being 0 bytes when I edit the node. I'm not sure why this is. At first I was thinking it might be a file permissions thing, but I don't think thats the case as the permissions look fine to me. To fix it all I had to do was re-upload the file. Problem is that there are hundreds of these files and I'd like to fix it just by making one update if that is possible.

2

There are 2 best solutions below

0
On

We had the same problem: a lot of 0 byte files in the database. What we did looked something like this:

function update_my_filesizes() {
    $fileIDs = db_query('SELECT fid FROM {file_managed) WHERE filesize = 0')->fetchCol();

    foreach(file_load_multiple($fids) as $file) {
        // determine size of file
        $filesize = SIZE_OF_THE_FILE; (pseudocode, we had to use filesize())
        $file->filesize = $filesize;

        if($file->filesize > 0) {        
            file_save($file);
        } else {
            echo "Filesize for file <filename here> is still 0 :(";
        }
    }
}
0
On

Here is a working version of Terry's pseudocode for Drupal 7.

$fids = db_query('SELECT fid FROM {file_managed} WHERE filesize = 0')->fetchCol();

foreach(file_load_multiple($fids) as $file) {
  // Get full path to file.
  $target = drupal_realpath($file->uri);
  // If the file does not exist try the next file.
  if (!file_exists($target)) {
    echo "File $file->uri does not exist." .PHP_EOL;
    continue;
  }
  // Find and store size of file
    $file->filesize = filesize($target);
    // Size of file is
    if ($file->filesize > 0) {
      file_save($file);
    }
    else {
      echo "Size of $file->uri is still zero." . PHP_EOL;
    }
}

Run it with drush:

drush php-script fix-file-sizes.php