переименовать файл загрузки, добавить новое имя в базу данных - PullRequest
1 голос
/ 28 января 2012

Я использую следующий код для загрузки и переименования файлов.Эта часть работает потрясающе, однако она также отправляет некоторые данные в таблицу базы данных.

Проблема в том, что старое имя публикуется в БД, но файл переименовывается в ID ... как я могу получить новое имя в БД?

Заранее спасибовот мой код:

 <?php

//This is the directory where images will be saved
$allowed_filetypes = array('.jpg','.pdf','.xlsx','.xls','.doc','.docx','.ppt','.pptx','.jpeg','.png','.gif','.pdf');
$max_filesize = 52428800; // max file size = 50MB
$target = $target . basename( $_FILES['document']['name']);


//This gets all the other information from the form
$billing_id=$_POST['billing_id'];
$shipping_id=$_POST['shipping_id'];
$file_name=$_POST['file_name'];
$file_type=$_POST['file_type'];
$file_description=$_POST['file_description'];

        $file = $_FILES['document']['name']; // Get the name of the file (including file extension).
        $ext = substr($file, strpos($file,'.'), strlen($file)-1);
        if(!in_array($ext,$allowed_filetypes))//check if file type is allowed
            die('The file extension you attempted to upload is not allowed.'); //not allowed
        if(filesize($_FILES['document']['tmp_name']) > $max_filesize) //check that filesize is less than 50MB
            die ('The file you attempted to upload is too large, compress it below 50MB.');


// Connects to your Database
mysql_connect("localhost", "root", "password") or die(mysql_error()) ;
mysql_select_db("table") or die(mysql_error()) ;

//Writes the information to the database
mysql_query("INSERT INTO customer_files (billing_id, shipping_id, file_name, file_type, file_description, file)
VALUES ('$billing_id', '$shipping_id', '$file_name', '$file_type', '$file_description', '$target')") ;

$target = "../../file_management/uploads/customers/" .mysql_insert_id() . $ext; 

//Writes the file to the server
if(move_uploaded_file($_FILES['document']['tmp_name'], $target))
{

//Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>

Ответы [ 2 ]

1 голос
/ 28 января 2012

Вы вставляете значения в базу данных перед тем, как переименовать файл.Вы должны внести изменения в свой код.Сначала вставьте идентификатор счета и доставки в базу данных, затем возьмите последний вставленный идентификатор, переименуйте файл с последним идентификатором вставки и обновите новое имя в базе данных.Измените свой код на:

<?php

   //This is the directory where images will be saved
   $allowed_filetypes =array('.jpg','.pdf','.xlsx','.xls','.doc','.docx','.ppt','.pptx','.jpeg','.png','.gif','.pdf');
   $max_filesize = 52428800; // max file size = 50MB
   $target = $target . basename( $_FILES['document']['name']);


   //This gets all the other information from the form
  $billing_id=$_POST['billing_id'];
  $shipping_id=$_POST['shipping_id'];
  $file_name=$_POST['file_name'];
  $file_type=$_POST['file_type'];
  $file_description=$_POST['file_description'];

    $file = $_FILES['document']['name']; // Get the name of the file (including file extension).
    $ext = substr($file, strpos($file,'.'), strlen($file)-1);
    if(!in_array($ext,$allowed_filetypes))//check if file type is allowed
        die('The file extension you attempted to upload is not allowed.'); //not allowed
    if(filesize($_FILES['document']['tmp_name']) > $max_filesize) //check that filesize is less than 50MB
        die ('The file you attempted to upload is too large, compress it below 50MB.');


    // Connects to your Database
     mysql_connect("localhost", "root", "password") or die(mysql_error()) ;
     mysql_select_db("table") or die(mysql_error()) ;

    //Writes the information to the database
   mysql_query("INSERT INTO customer_files (billing_id, shipping_id) VALUES ('$billing_id', '$shipping_id')") ;

  $target = "../../file_management/uploads/customers/" .mysql_insert_id() . $ext; 

  $last_id = mysql_insert_id();
  $new_file_name = mysql_insert_id() . $ext;

  mysql_query("UPDATE customer_files SET file_name='$new_file_name',file_type='$file_type',file_description='$file_description',file='$target' WHERE id=$last_id");


//Writes the file to the server
if(move_uploaded_file($_FILES['document']['tmp_name'], $target))
{

 //Tells you if its all ok
  echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {

//Gives and error if its not
 echo "Sorry, there was a problem uploading your file.";
}
?>

Надеюсь, это поможет

1 голос
/ 28 января 2012

Новое имя уже находится в БД - это первичный ключ записи, которая была создана при вставке данных для выгрузки:

$target = "../../file_management/uploads/customers/" .mysql_insert_id() . $ext;
                                                      ^^^^^^^^^^^^^^^^^ the new filename
...