jQuery ajax单文件上传

jQuery ajax single file upload

本问题已经有最佳答案,请猛点这里访问。

我知道这个问题被问了很多,我尝试了至少10种不同的代码来运行这个,但没有成功。我正试图用jquery.ajax上传一个文件,但它不起作用。下面的代码总是输出:"请选择一个文件",因为没有设置文件名或其他内容

HTML:

1
2
3
4
<form enctype="multipart/form-data">
  <input name="file" type="file" />
  <input type="button" value="Upload" />
</form>

jQuery:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$(function(){
  $(document).ready(function(){
    var files;

    $('input[type=file]').on('change', prepareUpload);
    function prepareUpload(event){
      files = event.target.files;
    };
    $(':button').click(function(){
        var formData = new FormData();
        $.each(files, function(key, value){
          formData.append(key, value);
        });
        alert(formData);
        $.ajax({
          url: 'check.php',  
          type: 'GET',
          data: formData,
          success: function(data){ $('#result').html(data); },
          cache: false,
          contentType: false,
          processData: false
        });
    });
  });
});

PHP:

1
2
3
4
5
6
7
8
9
10
if(isset($_GET['file'])){
    $filename = $_FILES['file']['name'];
    if(isset($filename) && !empty($filename)){
        echo 'sup my man?!';
    }else{
        echo 'please choose a file';
    }
}else{
    echo 'not set';
}

我不知道问题出在什么地方,我知道问题出在FormData对象创建中,因为警报——很好,不起作用。

顺便说一句,它将被写在jquery中对我来说非常重要。


after hours of搜索和寻找答案,最后让它!!!!!!!!!!!!!!!!!!!!!!!!!!!!!code is below:))))P></

HTML:P></

1
2
3
4
5
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>

jQuery的:P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$(function(){
    $('#uploadBTN').on('click', function(){
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField","This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

你可以在upload.php文件日期passed with the $_FILES['file']接入。P></

thanks for everyone想帮助:)P></

我在这里回答from the(with some changes)MDNP></


在文件数据文件。抓住from the FieldP></

thing to do is the first to the change事件在bind函数的在线文件和你在function for the场捕获文件的日期:P></

1
2
3
4
5
6
7
8
9
10
11
// Variable to store your files
var files;

// Add events
$('input[type=file]').on('change', prepareUpload);

// Grab the files and set them to our variable
function prepareUpload(event)
{
  files = event.target.files;
}

this to the文件节省文件日期变量for以后使用。P></

文件上传(handle the在线提交。P></

你提交的form is when the need to handle the文件上传自己的Ajax请求。add the following结合布尔函数:P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
$('form').on('submit', uploadFiles);

// Catch the form submit and upload the files
function uploadFiles(event)
{
  event.stopPropagation(); // Stop stuff happening
    event.preventDefault(); // Totally stop stuff happening

// START A LOADING SPINNER HERE

// Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value)
{
    data.append(key, value);
});

$.ajax({
    url: 'submit.php?files',
    type: 'POST',
    data: data,
    cache: false,
    dataType: 'json',
    processData: false, // Don't process the files
    contentType: false, // Set content type to false as jQuery will tell the server its a query string request
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            submitForm(event, data);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
        // STOP LOADING SPINNER
    }
});
}

function does is this是建立在微机上加以实现和每个文件对象appends to it.恩,我passes as a request to the服务器数据。need to be to 2属性集:虚假P></

  • 因为jQuery processData -将文件arrays convert into the字符串*服务器上不能读取它。
  • contenttype集this to虚假因为jQuery defaults to application/ WWW形态- X和不urlencoded send the files。setting it to also multipart /日期表或者不似乎工作。

c文件上传的茶。P></

快速和肮脏的文件上传的PHP脚本to the back some通和信息:P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<?php // You need to add server side validation and better error handling here

$data = array();

if(isset($_GET['files']))
{  
$error = false;
$files = array();

$uploaddir = './uploads/';
foreach($_FILES as $file)
{
    if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name'])))
    {
        $files[] = $uploaddir .$file['name'];
    }
    else
    {
        $error = true;
    }
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
}
else
{
    $data = array('success' => 'Form was submitted', 'formData' => $_POST);
}

echo json_encode($data);

?>

重要:不要使用this,写你自己的。P></

D handle the form submit。P></

the method of the function成功上传日期passes sent from the the back to the submit功能服务器。You can then that to the服务器通as part of your后:P></

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function submitForm(event, data)
{
  // Create a jQuery object from the form
$form = $(event.target);

// Serialize the form data
var formData = $form.serialize();

// You should sterilise the file names
$.each(data.files, function(key, value)
{
    formData = formData + '&filenames[]=' + value;
});

$.ajax({
    url: 'submit.php',
    type: 'POST',
    data: formData,
    cache: false,
    dataType: 'json',
    success: function(data, textStatus, jqXHR)
    {
        if(typeof data.error === 'undefined')
        {
            // Success so call function to process the form
            console.log('SUCCESS: ' + data.success);
        }
        else
        {
            // Handle errors here
            console.log('ERRORS: ' + data.error);
        }
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        // Handle errors here
        console.log('ERRORS: ' + textStatus);
    },
    complete: function()
    {
        // STOP LOADING SPINNER
    }
});
}

最终幻想的音符P></

This is an example脚本只你need to handle both,服务器端和客户端的方式确认和NOTIFY that the users to some文件上传是发生。在自制的GitHub项目*在线如果你想看到它的工作。P></

从referencedP></