在上传的文件中添加随机数 [英] Adding Random Number to Uploaded File

查看:222
本文介绍了在上传的文件中添加随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Valum的Ajax-Uploader脚本将文件上传到我的服务器.由于上传的文件很有可能具有相同的名称,因此我在文件名中添加了一个随机数.问题在于ajax上传器正在将原始文件名返回到input[type=text]中,而不是将新文件名添加到随机数中.我尝试使用echo $file;而不是echo "success";,但是所有发生的事情是文件已上传,脚本返回并显示弹出错误.

I'm using Valum's Ajax-Uploader script to upload files to my server. Because there's a good chance of the uploaded files have the same name I add a random number to the filename. The problem is that the ajax uploader is returning the original filename into the input[type=text] instead of the new filename with the random number added. I've tried echo $file; instead of echo "success"; , but all that happens is that the file is uploaded, and the script returns with the pop-up error.

jQuery(function() {
    var url = "http://example.com/uploads/samples/";
    var button = jQuery('#up');
    new AjaxUpload(button, {
        action: 'upload.php',
        name: 'upload',
        autoSubmit: true,
        onSubmit: function(file, ext) {
            // do stuff while file is uploading
        },
        onComplete: function(file, response) {
            if (response === "success") {
                $('input[type=text]').val(url + file);
            } else {
                jAlert('Something went wrong!', 'Error!');
            }
        }
    });
});

upload.php

<?php
    $uploaddir = '/path/to/uploaddir/'; 
    $file = basename($_FILES['file']['name']);

     if($_FILES['file']['name']) {
      $file = preg_replace('/\s+/', '_', $file);
      $rand = rand(0000,9999);

      if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $rand . $file)) { 
            echo "success";
        } else {
            echo "error";
        }
    }
?>

推荐答案

客户端代码和服务器代码完全独立存在.基本上,您的JavaScript代码无法知道您的PHP代码刚刚做了什么.在PHP文件中更改url时不会自动更新.

Client code and server code exist completely independently of each other. Basically, your JavaScript code has no way of knowing what your PHP code just did. url doesn't update automatically when you change it in the PHP file.

另一种解决方案是让您的PHP代码回显新文件名,或回显错误消息.

An alternate solution would be to have your PHP code echo the new filename, or echo an error message.

例如:

PHP

<?php
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $rand . $file)) {   
    // Everything went well! Echo the dollar sign ($) plus the new file name
    echo '$' . $_FILES['file']['tmp_name'], $uploaddir . $rand . $file;   
} else {  
    echo "error";  
}  
?>

JS

onComplete: function(file, response) { 
    // If the first character of the response is the "$" sign
    if (response.substring(0,1) == "$") { 
        $('input[type=text]').val(response.substring(1));
    } else { 
        jAlert('Something went wrong!', 'Error!'); 
    } 
} 

这篇关于在上传的文件中添加随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆