我想用jQuery异步上传文件。

$(文档).ready(函数(){$(“#uploadbutton”).click(函数(){var filename=$(“#file”).val();$.ajax美元({类型:“POST”,url:“addFile.do”,enctype:'多部分/表单数据',数据:{文件:文件名},成功:函数(){alert(“上传的数据:”);}});});});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js“></script><span>文件</span><input type=“file”id=“file”name=“file”size=“10”/><input id=“uploadbutton”type=“button”value=“Upload”/>

我只得到文件名,而不是上传文件。我可以做什么来解决这个问题?


当前回答

var formData=new FormData();
formData.append("fieldname","value");
formData.append("image",$('[name="filename"]')[0].files[0]);

$.ajax({
    url:"page.php",
    data:formData,
    type: 'POST',
    dataType:"JSON",
    cache: false,
    contentType: false,
    processData: false,
    success:function(data){ }
});

您可以使用表单数据发布包括图像在内的所有值。

其他回答

没有Jquery的现代方法是,当用户选择一个文件时,使用从<input type=“file”>返回的FileList对象,然后使用Fetch发布包裹在FormData对象周围的FileList。

// The input DOM element // <input type="file">
const inputElement = document.querySelector('input[type=file]');

// Listen for a file submit from user
inputElement.addEventListener('change', () => {
    const data = new FormData();
    data.append('file', inputElement.files[0]);
    data.append('imageName', 'flower');

    // You can then post it to your server.
    // Fetch can accept an object of type FormData on its  body
    fetch('/uploadImage', {
        method: 'POST',
        body: data
    });
});

您可以在这里看到一个工作演示的解决方案,该演示允许您预览表单文件并将其提交到服务器。对于您的情况,您需要使用Ajax来促进文件上传到服务器:

<from action="" id="formContent" method="post" enctype="multipart/form-data">
    <span>File</span>
    <input type="file" id="file" name="file" size="10"/>
    <input id="uploadbutton" type="button" value="Upload"/>
</form>

提交的数据是表单数据。在jQuery上,使用表单提交函数而不是单击按钮提交表单文件,如下所示。

$(document).ready(function () {
   $("#formContent").submit(function(e){

     e.preventDefault();
     var formdata = new FormData(this);

 $.ajax({
     url: "ajax_upload_image.php",
     type: "POST",
     data: formdata,
     mimeTypes:"multipart/form-data",
     contentType: false,
     cache: false,
     processData: false,
     success: function(){

     alert("successfully submitted");

     });
   });
});

查看更多详细信息

在此处查找“异步处理文件的上载过程”:https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

链接中的示例

<?php
if (isset($_FILES['myFile'])) {
    // Example:
    move_uploaded_file($_FILES['myFile']['tmp_name'], "uploads/" . $_FILES['myFile']['name']);
    exit;
}
?><!DOCTYPE html>
<html>
<head>
    <title>dnd binary upload</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script type="text/javascript">
        function sendFile(file) {
            var uri = "/index.php";
            var xhr = new XMLHttpRequest();
            var fd = new FormData();

            xhr.open("POST", uri, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // Handle response.
                    alert(xhr.responseText); // handle response.
                }
            };
            fd.append('myFile', file);
            // Initiate a multipart/form-data upload
            xhr.send(fd);
        }

        window.onload = function() {
            var dropzone = document.getElementById("dropzone");
            dropzone.ondragover = dropzone.ondragenter = function(event) {
                event.stopPropagation();
                event.preventDefault();
            }

            dropzone.ondrop = function(event) {
                event.stopPropagation();
                event.preventDefault();

                var filesArray = event.dataTransfer.files;
                for (var i=0; i<filesArray.length; i++) {
                    sendFile(filesArray[i]);
                }
            }
        }
    </script>
</head>
<body>
    <div>
        <div id="dropzone" style="margin:30px; width:500px; height:300px; border:1px dotted grey;">Drag & drop your file here...</div>
    </div>
</body>
</html>

使用HTML5,您可以使用Ajax和jQuery上传文件。不仅如此,您还可以进行文件验证(名称、大小和MIME类型)或使用HTML5进度标记(或div)处理进度事件。最近我不得不做一个文件上传器,但我不想使用Flash或Iframes或插件,经过一些研究,我想出了解决方案。

HTML:

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

首先,如果需要,可以进行一些验证。例如,在文件的.on('change')事件中:

$(':file').on('change', function () {
  var file = this.files[0];

  if (file.size > 1024) {
    alert('max upload size is 1k');
  }

  // Also see .name, .type
});

现在,单击按钮即可提交$.ajax():

$(':button').on('click', function () {
  $.ajax({
    // Your server script to process the upload
    url: 'upload.php',
    type: 'POST',

    // Form data
    data: new FormData($('form')[0]),

    // Tell jQuery not to process data or worry about content-type
    // You *must* include these options!
    cache: false,
    contentType: false,
    processData: false,

    // Custom XMLHttpRequest
    xhr: function () {
      var myXhr = $.ajaxSettings.xhr();
      if (myXhr.upload) {
        // For handling the progress of the upload
        myXhr.upload.addEventListener('progress', function (e) {
          if (e.lengthComputable) {
            $('progress').attr({
              value: e.loaded,
              max: e.total,
            });
          }
        }, false);
      }
      return myXhr;
    }
  });
});

正如你所看到的,通过HTML5(以及一些研究)文件上传不仅变得可能,而且非常容易。尝试使用Google Chrome,因为示例中的一些HTML5组件在每个浏览器中都不可用。

你可以很容易地用普通JavaScript实现。以下是我当前项目的片段:

var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(e) {
    var percent = (e.position/ e.totalSize);
    // Render a pretty progress bar
};
xhr.onreadystatechange = function(e) {
    if(this.readyState === 4) {
        // Handle file upload complete
    }
};
xhr.open('POST', '/upload', true);
xhr.setRequestHeader('X-FileName',file.name); // Pass the filename along
xhr.send(file);