PHP通过AJAX / HTML 5重命名文件上传图像

时间:2012-12-04 01:19:32

标签: php ajax file-upload

我不擅长阅读通过php / ajax上传图片的代码,所以我希望一个php大师可以帮助我。我正在尝试获取图像文件名,如果它中有空格,则用下划线替换这些空格“_”

用于上传的php代码是:

$file_name  = ( isset($_REQUEST['ax-file-name']) && !empty($_REQUEST['ax-file-name']) )?$_REQUEST['ax-file-name']:'';
$currByte   = isset($_REQUEST['ax-start-byte'])?$_REQUEST['ax-start-byte']:0;

if($is_ajax)//Ajax Upload, FormData Upload and FF3.6 php:/input upload
{   
    //we get the path only for the first chunk
    $full_path  = ($currByte==0) ? checkFileExits($file_name, $upload_path):$upload_path.$file_name;

    //Just optional, avoid to write on exisiting file, but in theory filename should be unique from the checkFileExits function
    $flag       = ($currByte==0) ? 0:FILE_APPEND;

    //formData post files just normal upload in $_FILES, older ajax upload post it in input
    $post_bytes = isset($_FILES['Filedata'])? file_get_contents($_FILES['Filedata']['tmp_name']):file_get_contents('php://input');

    //some rare times (on very very fast connection), file_put_contents will be unable to write on the file, so we try until it writes
    while(@file_put_contents($full_path, $post_bytes, $flag) === false)
    {
        usleep(50);
    }

    //delete the temporany chunk
    if(isset($_FILES['Filedata']))
    {
        @unlink($_FILES['Filedata']['tmp_name']);
    }

    //if it is not the last chunk just return success chunk upload
    if($isLast!='true')
    {
        echo json_encode(array('name'=>basename($full_path), 'size'=>$full_size, 'status'=>1, 'info'=>'Chunk uploaded'));
    }
}
else //Normal html and flash upload
{
    $isLast     = 'true';//we cannot upload by chunks here so assume it is the last single chunk
    $full_path  = checkFileExits($file_name, $upload_path);
    $result     = move_uploaded_file(str_replace(" ", "_",$_FILES['Filedata']['tmp_name']), $full_path);//make the upload
    if(!$result) //if any error return the error
    {
        echo json_encode( array('name'=>basename($full_path), 'size'=>$full_size, 'status'=>-1, 'info'=>'File move error') );
        return  false;
    }
}

我已经尝试了以下内容(使用 str_replace(“”,“_”,$ nameoffile)

$post_bytes = isset($_FILES['Filedata'])? file_get_contents(str_replace(" ", "_",$_FILES['Filedata']['tmp_name'])):file_get_contents('php://input');

似乎没有重命名它。那么我在哪里错过了它?

1 个答案:

答案 0 :(得分:0)

您的代码中的问题是,您尝试重命名图像文件的临时名称而不是实际名称

move_uploaded_file(str_replace(" ", "_",$_FILES['Filedata']['tmp_name']), $full_path);//make the upload 

所以你必须从临时名称中删除str_replace并将其附加到这样的实际名称。

move_uploaded_file($_FILES['Filedata']['tmp_name'], str_replace(" ", "_",$full_path));//make the upload 

希望它澄清你的怀疑。