从mini-upload-form返回新文件名

时间:2015-05-11 19:40:41

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

我正在使用Mini AJAX Upload Form将文件上传到服务器。我修改了上传代码,在文件末尾添加了一个时间戳。如何将文件的新名称(带有时间戳)返回给客户端以供以后使用?

date_default_timezone_set('America/New_York'); 
$date = date('.YmdHis');
// A list of permitted file extensions
$allowed = array('sqlite', 'db', 'db3');
if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){

    $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);

    if(!in_array(strtolower($extension), $allowed)){
            echo '{"status":"error"}';
            exit;
    }

    $file =  '/var/www/html/uploads/'.$_FILES['upl']['name'].$date;

    if(move_uploaded_file($_FILES['upl']['tmp_name'], $file)){
            echo '{"status":"success"}';
            exit;
    }
}
echo '{"status":"error"}';
exit;

JS:

$(function(){

 $('#drop a').click(function(){
    // Simulate a click on the file input button
    // to show the file browser dialog
    $(this).parent().find('input').click();
 });

 // Initialize the jQuery File Upload plugin
 $('#upload').fileupload({

    url: 'includes/php/upload.php',

    // This element will accept file drag/drop uploading
    dropZone: $('#drop'),
 });

 // Prevent the default action when a file is dropped on the window
 $(document).on('drop dragover', function (e) {
    e.preventDefault();
 });
});

HTML片段:

<div class="row">
 <div class="col-lg-12 text-center">
  <form id="upload" method="post" enctype="multipart/form-data">
   <div id="drop">
    <p>Drop Database Here</p>
    <a>Browse</a>
    <input type="file" name="upl" multiple/>
   </div>
  </form>
 </div>
</div>

注意:迷你AJAX上传表单使用jQuery-File-Upload

1 个答案:

答案 0 :(得分:0)

你可以使用完成回调来上传后获取文件名,当然你需要在你的PHP脚本中将它写回你的ajax

done: function (e, data) {
            $("tr:has(td)").remove();
            $.each(data.result, function (index, file) {

                $("#uploaded-files").append(
                        $('<tr/>')
                        .append($('<td/>').text(file.fileName))
                        .append($('<td/>').text(file.fileSize))
                        .append($('<td/>').text(file.fileType))
                        .append($('<td/>').html("<a href='upload?f="+index+"'>Click</a>"))
                        .append($('<td/>').text("@"+file.twitter))

                        )//end $("#uploaded-files").append()
            }); 
        },

此示例也是java示例,但它们与您的操作类似 http://hmkcode.com/java-servlet-jquery-file-upload/