jQuery AJAX 单文件上传

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21214608/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:29:07  来源:igfitidea点击:

jQuery AJAX single file upload

jquery

提问by user3195129

I know this question has been asked a lot, and I tried at least 10 different codes to run this without success.

我知道这个问题被问了很多,我尝试了至少 10 种不同的代码来运行它,但没有成功。

I'm trying to upload a single file with jQuery.ajax(), but it doesn't work. The code below always outputs:

我正在尝试使用 上传单个文件jQuery.ajax(),但它不起作用。下面的代码总是输出:

please choose a file' because the file's name is not set or something

请选择一个文件'因为文件名未设置或其他



HTML

HTML

<form enctype="multipart/form-data">
  <input name="file" type="file" />
  <input type="button" value="Upload" />
</form>
<div id="result"></div>

jQuery

jQuery

$(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

PHP

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';
}

I don't know what the problem is, I know it's in the FormDataobject creation because the alert - good to go, doesn't work.

我不知道问题是什么,我知道它在FormData对象创建中,因为警报 - 很好,不起作用。

BTW it is really important for me that it would be written in jQuery.

顺便说一句,它将用 jQuery 编写对我来说非常重要。

回答by user3195129

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

经过数小时的搜索和寻找答案,我终于成功了!!!!!代码如下:))))

HTML:

HTML:

<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>
<div id="output"></div>

jQuery:

jQuery:

$(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
        });
    });
});

In the upload.phpfile you can access the data passed with $_FILES['file'].

upload.php文件中,您可以访问通过$_FILES['file'].

Thanks everyone for trying to help:)

谢谢大家的帮助:)

I took the answer from here (with some changes) MDN

我从这里得到了答案(有一些变化) MDN

回答by CodeMonk

A. Grab file data from the file field

A. 从​​文件字段中抓取文件数据

The first thing to do is bind a function to the change event on your file field and a function for grabbing the file data:

首先要做的是将一个函数绑定到文件字段上的更改事件和一个用于获取文件数据的函数:

// 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 saves the file data to a file variable for later use.

这会将文件数据保存到文件变量中以备后用。

B. Handle the file upload on submit

B. 在提交时处理文件上传

When the form is submitted you need to handle the file upload in its own AJAX request. Add the following binding and function:

提交表单时,您需要在其自己的 AJAX 请求中处理文件上传。添加以下绑定和函数:

$('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
    }
});
}

What this function does is create a new formData object and appends each file to it. It then passes that data as a request to the server. 2 attributes need to be set to false:

这个函数的作用是创建一个新的 formData 对象并将每个文件附加到它。然后它将该数据作为请求传递给服务器。2个属性需要设置为false:

  • processData - Because jQuery will convert the files arrays into strings and the server can't pick it up.
  • contentType - Set this to false because jQuery defaults to application/x-www-form-urlencoded and doesn't send the files. Also setting it to multipart/form-data doesn't seem to work either.
  • processData - 因为 jQuery 会将文件数组转换为字符串,而服务器无法获取它。
  • contentType - 将此设置为 false,因为 jQuery 默认为 application/x-www-form-urlencoded 并且不发送文件。还将其设置为 multipart/form-data 似乎也不起作用。

C. Upload the files

C. 上传文件

Quick and dirty php script to upload the files and pass back some info:

上传文件并传回一些信息的快速而肮脏的 php 脚本:

<?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);

?>

IMP: Don't use this, write your own.

IMP:不要用这个,自己写。

D. Handle the form submit

D. 处理表单提交

The success method of the upload function passes the data sent back from the server to the submit function. You can then pass that to the server as part of your post:

上传函数的成功方法将从服务器发回的数据传递给提交函数。然后,您可以将其作为帖子的一部分传递给服务器:

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
    }
});
}

Final note

最后说明

This script is an example only, you'll need to handle both server and client side validation and some way to notify users that the file upload is happening. I made a project for it on Githubif you want to see it working.

此脚本只是一个示例,您需要处理服务器端和客户端验证以及某种通知用户文件上传正在发生的方法。如果你想看到它的工作,我在Github上为它做了一个项目。

Referenced From

引用自