du_1993 2014-08-27 21:24
浏览 26
已采纳

Php多张照片上传和重命名

My problem recently arose when I tried to change save a picture to a location with a different name. eg. saving a picture called hello.jpg to a location called /sets/1/09092014-1.jpg

Here is my code:

if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
$today = date("dmY");
$Title =  $today."-".$x.".jpg";
$x ++;
$url = "/Sets/".$desired_dir."/".$Title;

$query = "INSERT INTO photo(name, url, album) VALUES('$Title', '$url', '$set')";
$result = mysql_query($query) OR DIE(mysql_error());


if($file_size > 10485760){
$errors[]='File size must be less than 2 MB';
}
if(empty($errors)==true){
if(is_dir("Sets/"."$desired_dir")==false){
mkdir("Sets/"."$desired_dir", 0700);
}
if(is_dir("Sets/"."$desired_dir/".$Title)==false){
rename ($file_tmp ,  $Title );
move_uploaded_file($file_tmp, "/Sets/$desired_dir/$file_tmp");
}else{
}

not including the DB stuff at the top.

I spent a while on this, and found that i may need to use the rename() method to rename the file before i save it, which I tried, but once again it didnt work.

When run, it adds the info to the database, creates the folder to be put in if not present, but then does not add the files.

Thanks, Waq

  • 写回答

1条回答 默认 最新

  • duanliang8464 2014-08-27 22:34
    关注

    According to your explanation you should not need to use $_SERVER["DOCUMENTE_ROOT"] at all. You just need to pay attention to file structure and your code. Here is corrected code with comments:

    if(empty($errors)==true){
    // $desired_dir didn't need parenthesis, buts its ok to use them
    // Remember directories and file names are case sensitive: Sets is != to sets
    if(is_dir("Sets/".$desired_dir)==false){
    // If your server is picky you can try 0755 here and change it lower later
    mkdir("Sets/".$desired_dir, 0700);
    }
    // ERROR your if test is supplying a file but you were testing for directory
    // $Title is a file not a directory
    if(is_file("Sets/".$desired_dir."/".$Title)==false){
    rename ($file_tmp,$Title);
    // You just renamed $file_tmp so change the blow code to use the right file
    // Because of the rename $file_tmp no longer exists
    move_uploaded_file($Title,"Sets/$desired_dir/$Title");
    }else{
    // It already exists, handle it
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 连续两帧图像高速减法
  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写