使用AJAX重命名上传的文件

时间:2015-08-13 04:30:40

标签: javascript php jquery ajax

我尝试使用SitePoint Drag and Drop file upload将图片上传到我的网站。我的cshtml页面包含当前用户的表单和userID。我想将文件重命名为userID,但AJAX异步上传图像而不发送userID数据。因此,我无法重命名该文件。如何通过JS / AJAX将userID从cshtml页面传递到php页面,以便能够重命名文件?

这是cshtml:

 <form id="upload" action="test2.php" method="POST" enctype="multipart/form-data">
   <input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />

                    <label for="fileselect">Files to upload:</label>
                    <input type="file" id="fileselect" name="fileselect[]" accept="image" />
                    <input type="text" id="id" name="id" value="@userID" hidden /> //This is referencing a SQL query to get the UserID
//It's the data I want to pass along

                    <div id="filedrag">or drop files here</div>

 <script src="filedrag.js"></script>

这是PHP:

$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] :    false);
$userID = ???

if ($fn) {
$file_ext = substr($fn, strripos($fn, '.'));
$newfilename = $userID.$file_ext;
// AJAX call
file_put_contents(
    'uploads/' . $newfilename,
    file_get_contents('php://input')
);
echo "$fn uploaded";
exit();

这是完整的JS:

(function() {

// getElementById
function $id(id) {
    return document.getElementById(id);
}
// output information
function Output(msg) {
    var m = $id("messages");
    m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
    e.stopPropagation();
    e.preventDefault();
    e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {

    // cancel event and hover styling
    FileDragHover(e);

    // fetch FileList object
    var files = e.target.files || e.dataTransfer.files;

    // process all File objects
    for (var i = 0, f; f = files[i]; i++) {
        ParseFile(f);
        UploadFile(f);
    }
}
// output file information
function ParseFile(file) {

    Output(
        "<p>File information: <strong>" + file.name +
        "</strong> type: <strong>" + file.type +
        "</strong> size: <strong>" + file.size +
        "</strong> bytes</p>"
    );

    // display an image
    if (file.type.indexOf("image") == 0) {
        var reader = new FileReader();
        reader.onload = function(e) {
            Output(
                "<p><strong>" + file.name + ":</strong><br />" +
                '<img src="' + e.target.result + '" /></p>'
            );
        }
        reader.readAsDataURL(file);
    }

    // display text
    if (file.type.indexOf("text") == 0) {
        var reader = new FileReader();
        reader.onload = function(e) {
            Output(
                "<p><strong>" + file.name + ":</strong></p><pre>" +
                e.target.result.replace(/</g, "&lt;").replace(/>/g, "&gt;") +
                "</pre>"
            );
        }
        reader.readAsText(file);
    }
}
// upload JPEG files
function UploadFile(file) {

    // following line is not necessary: prevents running on SitePoint servers
    if (location.host.indexOf("sitepointstatic") >= 0) return

    var xhr = new XMLHttpRequest();
    if (xhr.upload && file.type == "image/jpeg" && file.size <= $id("MAX_FILE_SIZE").value) {

        // create progress bar
        var o = $id("progress");
        var progress = o.appendChild(document.createElement("p"));
        progress.appendChild(document.createTextNode("upload " + file.name));

        // progress bar
        xhr.upload.addEventListener("progress", function(e) {
            var pc = parseInt(100 - (e.loaded / e.total * 100));
            progress.style.backgroundPosition = pc + "% 0";
        }, false);

        // file received/failed
        xhr.onreadystatechange = function(e) {
            if (xhr.readyState == 4) {
                progress.className = (xhr.status == 200 ? "success" : "failure");
            }
        };

        // start upload
        xhr.open("POST", $id("upload").action, true);
        xhr.setRequestHeader("X_FILENAME", file.name);
        xhr.send(file);
    }
}
// initialize
function Init() {

    var fileselect = $id("fileselect"),
        filedrag = $id("filedrag"),
        submitbutton = $id("submitbutton");

    // file select
    fileselect.addEventListener("change", FileSelectHandler, false);

    // is XHR2 available?
    var xhr = new XMLHttpRequest();
    if (xhr.upload) {

        // file drop
        filedrag.addEventListener("dragover", FileDragHover, false);
        filedrag.addEventListener("dragleave", FileDragHover, false);
        filedrag.addEventListener("drop", FileSelectHandler, false);
        filedrag.style.display = "block";
    }
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
    Init();
}
})();

0 个答案:

没有答案