0

我不擅长阅读通过 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(" ", "_", $nameofile)

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

这似乎对重命名它没有任何作用。那么我在哪里想念它?

4

1 回答 1

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 

希望它能澄清你的疑问。

于 2012-12-04T02:05:39.503 回答