简体   繁体   中英

trying to upload a file using HTML5 and ajax

I have been attempting to get a nice neat file upload using ajax, and from the many items on SO I have been able to get the framework done as follows: My HTML:

    <form enctype="multipart/form-data" method="post">
<input name="file" type="file" />
<input type="button" value="Upload" />

Pretty straight forward.

My PHP storeSales.php

    if ($_FILES["file"]["name"] != NULL) { 
if (file_exists("accounting/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
move_uploaded_file($_FILES["file"]["tmp_name"], "accounting/" . $_FILES["file"]["name"]);
}
}
$file = fopen($_FILES['myfile']['name'],'r') or die('cant open file');

and my .js:

    $(":button").click(function(){
var formData = new FormData($('form')[0]); if (formData !=null) {
alert("Got the file");
} else {
alert("nothing Here"); 
}

$.ajax({
    url: 'storeSales.php',  //Server script to process data
    type: 'POST',
    xhr: function() {  // Custom XMLHttpRequest
        var myXhr = $.ajaxSettings.xhr();
        if(myXhr.upload){ // Check if upload property exists
            myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
        }
        return myXhr;
    },
    //Ajax events

    success: function(result)
{
    console.log($.ajaxSettings.xhr().upload);
    alert(result);
},

    // Form data
    data: formData,
    //Options to tell jQuery not to process data or worry about content-type.
    cache: false,
    contentType: false,
    processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
    $('progress').attr({value:e.loaded,max:e.total});
}
}

When I try to upload a file, I get the alert in my .js file that says "Got the file" but in the php code I get the error that a file cannot be empty. From everything I have been able to find, I thought I was doing the php correctly. what is the correct way to handle this? Am I missing something else?

You can't use ajax to upload files - it's an illegal operation (via the dry Ajax route) without a third-party script. In short, you can't pass $_FILES data via Ajax. Only $_POST data. You need to find a plugin.

Try Uploadify : http://www.uploadify.com/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM