如何在jquery文件上传中重命名文件

时间:2015-10-07 10:38:55

标签: php jquery ajax uploadify jquery-file-upload

  

嗨,我是jquery的新手。我试图在上传时重命名该文件..但我无法这样做

     

我用于文件上传的代码

 $(function() {
var btnUpload=$('#upload');

var status=$('#status');
    new AjaxUpload(btnUpload, {
action: 'upload-file.php',
name: 'uploadfile',
    onSubmit: function(finalname, ext){
if (! (ext && /^(pdf|doc|docx|xls|xlsx|text|)$/.test(ext))){ 
status.text('Only pdf, xls,doc,docs,xlsx and text files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(finalname, response){
status.text('');
if(response==="success"){
$('#head').val(finalname);
} else{
status.text('Upload Failed');
}
    }
});
  

Php Code

$uploaddir = 'uploads/files/'; 
$file = $uploaddir . basename($_FILES['uploadfile']['name']); 
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) { 
  echo "success"; 
} else {

    echo "error";
}
  

HTML

<div id="upload" ><span>Browse<span></div><span id="status" ></span>
<input type="text" id="head" name="head" value="">
  

我可以用php文件重命名...但是在jquery代码中它没有给我错误的文件名,请帮助

1 个答案:

答案 0 :(得分:1)

  

我设法在上传之前重命名文件名... pepole down尽管有所帮助。我对我的代码所做的更改可能对其他人有用

 $(function() {
    var btnUpload=$('#upload');
var status=$('#status');
var mm=Math.random().toString(36).substring(7) + new Date().getTime(); //to add new name of file
new AjaxUpload(btnUpload, {
action: 'upload-file.php?name='+mm, // gave a action to php file so i can use the same name
name: 'uploadfile',
onSubmit: function(file, ext){
 if (! (ext && /^(pdf|doc|docx|xls|xlsx|text|)$/.test(ext))){ 
status.text('Only pdf, xls,doc,docs,xlsx and text files are allowed');
return false;
}
status.text('Uploading...');
},
onComplete: function(file, response){
var fileExtension = '.' + file.split('.').pop(); //got the file extestion
var outputfile = file.substr(0, file.lastIndexOf('.')) || file; //got the file name
var spaceremoved=outputfile.replace(/\s/g, '');//removed the space from file
var filename=mm+spaceremoved+fileExtension; //merged all to one
    status.text('');
if(response==="success"){
    $('#head').val(filename);
    } else{
}
    }
    });
  

我在php文件中所做的更改

$uploaddir = 'uploads/files/'; 
if(isset($_GET['name'])){
$filena=$_GET['name'];
}
$basename=$filena.basename($_FILES['uploadfile']['name']);//merged the name
$finalna=preg_replace('/\s+/', '', $basename);//removed the space
$file = $uploaddir .$finalna;// merged to final 
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) { 
  echo "success"; 
} else {
    echo "error";
}