我可以使用以下jQuery代码使用ajax请求的POST方法执行文件上载吗?

$.ajax({
    type: "POST",
    timeout: 50000,
    url: url,
    data: dataString,
    success: function (data) {
        alert('success');
        return false;
    }
});

如果可能,我需要填写数据部分吗?这是正确的方式吗?我只将文件POST到服务器端。

我一直在搜索,但我发现的是一个插件,而在我的计划中,我不想使用它。至少目前是这样。


无法通过AJAX上载文件。您可以上传文件,而无需使用IFrame刷新页面。您可以在此处查看更多详细信息。


更新

XHR2支持通过AJAX上传文件。例如,通过FormData对象,但遗憾的是,它不受所有/旧浏览器的支持。

FormData支持从以下桌面浏览器版本开始。

即10+Firefox 4.0+铬7+Safari 5+歌剧12+

有关详细信息,请参阅MDN链接。


使用隐藏的iframe并将表单的目标设置为该iframe的名称。这样,当提交表单时,只会刷新iframe。为iframe的加载事件注册一个事件处理程序,以解析响应。


使用XMLHttpRequest()确实可以进行AJAX上载。无需iframes。可以显示上载进度。

有关详细信息,请参阅:答案https://stackoverflow.com/a/4943774/873282对jQuery Upload Progress和AJAX文件上传提出质疑。


通过ajax上传文件不再需要Iframes。我最近自己做过。查看以下页面:

使用AJAX和jQuery上传HTML5文件

http://dev.w3.org/2006/webapi/FileAPI/#FileReader-界面

更新了答案并进行了清理。使用getSize函数检查大小或使用getType函数检查类型。添加了progressbar html和css代码。

var Upload = function (file) {
    this.file = file;
};

Upload.prototype.getType = function() {
    return this.file.type;
};
Upload.prototype.getSize = function() {
    return this.file.size;
};
Upload.prototype.getName = function() {
    return this.file.name;
};
Upload.prototype.doUpload = function () {
    var that = this;
    var formData = new FormData();

    // add assoc key values, this will be posts values
    formData.append("file", this.file, this.getName());
    formData.append("upload_file", true);

    $.ajax({
        type: "POST",
        url: "script",
        xhr: function () {
            var myXhr = $.ajaxSettings.xhr();
            if (myXhr.upload) {
                myXhr.upload.addEventListener('progress', that.progressHandling, false);
            }
            return myXhr;
        },
        success: function (data) {
            // your callback here
        },
        error: function (error) {
            // handle error
        },
        async: true,
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        timeout: 60000
    });
};

Upload.prototype.progressHandling = function (event) {
    var percent = 0;
    var position = event.loaded || event.position;
    var total = event.total;
    var progress_bar_id = "#progress-wrp";
    if (event.lengthComputable) {
        percent = Math.ceil(position / total * 100);
    }
    // update progressbars classes so it fits your code
    $(progress_bar_id + " .progress-bar").css("width", +percent + "%");
    $(progress_bar_id + " .status").text(percent + "%");
};

如何使用Upload类

//Change id to your id
$("#ingredient_file").on("change", function (e) {
    var file = $(this)[0].files[0];
    var upload = new Upload(file);

    // maby check size or type here with upload.getSize() and upload.getType()

    // execute upload
    upload.doUpload();
});

Progressbar html代码

<div id="progress-wrp">
    <div class="progress-bar"></div>
    <div class="status">0%</div>
</div>

Progressbar css代码

#progress-wrp {
  border: 1px solid #0099CC;
  padding: 1px;
  position: relative;
  height: 30px;
  border-radius: 3px;
  margin: 10px;
  text-align: left;
  background: #fff;
  box-shadow: inset 1px 3px 6px rgba(0, 0, 0, 0.12);
}

#progress-wrp .progress-bar {
  height: 100%;
  border-radius: 3px;
  background-color: #f39ac7;
  width: 0;
  box-shadow: inset 1px 1px 10px rgba(0, 0, 0, 0.11);
}

#progress-wrp .status {
  top: 3px;
  left: 50%;
  position: absolute;
  display: inline-block;
  color: #000000;
}

如果你想这样做:

$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
    if( progressEvent.lengthComputable) {
        var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
        if( upload) {
            console.log( percent + ' uploaded');
        } else {
            console.log( percent + ' downloaded');
        }
    }
})
.done( function() {
    console.log( 'Finished upload');                    
});

https://github.com/lgersman/jquery.orangevolt-ampere/blob/master/src/jquery.upload.js

可能是您的解决方案。


$("#submit_car").click(function() {
  var formData = new FormData($('#car_cost_form')[0]);
  $.ajax({
     url: 'car_costs.php',
     data: formData,
     contentType: false,
     processData: false,
     cache: false,
     type: 'POST',
     success: function(data) {
       // ...
     },
  });
});

编辑:注释内容类型和过程数据您可以简单地使用它通过Ajax上传文件。。。。。。提交输入不能在表单元素之外:)


我想到了一个主意:

Have an iframe on page and have a referencer.

具有将输入类型文件元素移动到的表单。

Form:  A processing page AND a target of the FRAME.

结果将发布到iframe,然后您只需将获取的数据发送到所需的图像标签,如下所示:

data:image/png;base64,asdfasdfasdfasdfa

并加载页面。

我相信这对我来说是有效的,取决于你是否能够做到:

.aftersubmit(function(){
    stopPropagation(); // or some other code which would prevent a refresh.
});

您可以使用ajaxSubmit方法,如下所示:)当您选择需要上传到服务器的文件时,表单将提交到服务器:)

$(document).ready(function () {
    var options = {
    target: '#output',   // target element(s) to be updated with server response
    timeout: 30000,
    error: function (jqXHR, textStatus) {
            $('#output').html('have any error');
            return false;
        }
    },
    success: afterSuccess,  // post-submit callback
    resetForm: true
            // reset the form after successful submit
};

$('#idOfInputFile').on('change', function () {
    $('#idOfForm').ajaxSubmit(options);
    // always return false to prevent standard browser submit and page navigation
    return false;
});
});

我已经很晚了,但我正在寻找一个基于ajax的图像上传解决方案,我正在寻找的答案在这篇文章中有点分散。我确定的解决方案涉及FormData对象。我组装了一个基本形式的代码。您可以看到它演示了如何使用fd.append()向表单添加自定义字段,以及如何在完成ajax请求时处理响应数据。

上传html:

<!DOCTYPE html>
<html>
<head>
    <title>Image Upload Form</title>
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        function submitForm() {
            console.log("submit event");
            var fd = new FormData(document.getElementById("fileinfo"));
            fd.append("label", "WEBUPLOAD");
            $.ajax({
              url: "upload.php",
              type: "POST",
              data: fd,
              processData: false,  // tell jQuery not to process the data
              contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                console.log("PHP Output:");
                console.log( data );
            });
            return false;
        }
    </script>
</head>

<body>
    <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
        <label>Select a file:</label><br>
        <input type="file" name="file" required />
        <input type="submit" value="Upload" />
    </form>
    <div id="output"></div>
</body>
</html>

如果您使用php,这里有一种处理上传的方法,包括使用上面html中演示的两个自定义字段。

上传.php

<?php
if ($_POST["label"]) {
    $label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
    if ($_FILES["file"]["error"] > 0) {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
    } else {
        $filename = $label.$_FILES["file"]["name"];
        echo "Upload: " . $_FILES["file"]["name"] . "<br>";
        echo "Type: " . $_FILES["file"]["type"] . "<br>";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";

        if (file_exists("uploads/" . $filename)) {
            echo $filename . " already exists. ";
        } else {
            move_uploaded_file($_FILES["file"]["tmp_name"],
            "uploads/" . $filename);
            echo "Stored in: " . "uploads/" . $filename;
        }
    }
} else {
    echo "Invalid file";
}
?>

Ajax发布和上传文件是可能的。我使用jQuery$.ajax函数加载文件。我尝试使用XHR对象,但无法在服务器端使用PHP获得结果。

var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);

$.ajax({
       url : 'upload.php',
       type : 'POST',
       data : formData,
       processData: false,  // tell jQuery not to process the data
       contentType: false,  // tell jQuery not to set contentType
       success : function(data) {
           console.log(data);
           alert(data);
       }
});

如您所见,您必须创建一个FormData对象,该对象为空或来自(serialized?-$('#yourForm').serialize())现有表单,然后附加输入文件。

以下是更多信息:-如何使用jQuery.ajax和FormData上载文件-通过jQuery上载文件,提供对象FormData,没有文件名,GET请求

对于PHP进程,您可以使用以下内容:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamaño permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no terminó la acción de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningún archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}

可以,只需使用javascript获取文件,确保将文件作为数据URL读取。解析出base64之前的内容,以实际获得base64编码的数据,然后如果您使用php或任何后端语言,您可以解码base64数据并保存到如下所示的文件中

Javascript:
var reader = new FileReader();
reader.onloadend = function ()
{
  dataToBeSent = reader.result.split("base64,")[1];
  $.post(url, {data:dataToBeSent});
}
reader.readAsDataURL(this.files[0]);


PHP:
    file_put_contents('my.pdf', base64_decode($_POST["data"]));

当然,你可能会想做一些验证,比如检查你正在处理的文件类型之类的事情,但这是一个想法。


在通过ajax从预览中删除不需要的文件后,我实现了一个即时预览和上传的多文件选择。

详细文档可在以下位置找到:http://anasthecoder.blogspot.ae/2014/12/multi-file-select-preview-without.html

演示:http://jsfiddle.net/anas/6v8Kz/7/embedded/result/

jsFiddle:http://jsfiddle.net/anas/6v8Kz/7/

Java脚本:

    $(document).ready(function(){
    $('form').submit(function(ev){
        $('.overlay').show();
        $(window).scrollTop(0);
        return upload_images_selected(ev, ev.target);
    })
})
function add_new_file_uploader(addBtn) {
    var currentRow = $(addBtn).parent().parent();
    var newRow = $(currentRow).clone();
    $(newRow).find('.previewImage, .imagePreviewTable').hide();
    $(newRow).find('.removeButton').show();
    $(newRow).find('table.imagePreviewTable').find('tr').remove();
    $(newRow).find('input.multipleImageFileInput').val('');
    $(addBtn).parent().parent().parent().append(newRow);
}

function remove_file_uploader(removeBtn) {
    $(removeBtn).parent().parent().remove();
}

function show_image_preview(file_selector) {
    //files selected using current file selector
    var files = file_selector.files;
    //Container of image previews
    var imageContainer = $(file_selector).next('table.imagePreviewTable');
    //Number of images selected
    var number_of_images = files.length;
    //Build image preview row
    var imagePreviewRow = $('<tr class="imagePreviewRow_0"><td valign=top style="width: 510px;"></td>' +
        '<td valign=top><input type="button" value="X" title="Remove Image" class="removeImageButton" imageIndex="0" onclick="remove_selected_image(this)" /></td>' +
        '</tr> ');
    //Add image preview row
    $(imageContainer).html(imagePreviewRow);
    if (number_of_images > 1) {
        for (var i =1; i<number_of_images; i++) {
            /**
             *Generate class name of the respective image container appending index of selected images, 
             *sothat we can match images selected and the one which is previewed
             */
            var newImagePreviewRow = $(imagePreviewRow).clone().removeClass('imagePreviewRow_0').addClass('imagePreviewRow_'+i);
            $(newImagePreviewRow).find('input[type="button"]').attr('imageIndex', i);
            $(imageContainer).append(newImagePreviewRow);
        }
    }
    for (var i = 0; i < files.length; i++) {
        var file = files[i];
        /**
         * Allow only images
         */
        var imageType = /image.*/;
        if (!file.type.match(imageType)) {
          continue;
        }

        /**
         * Create an image dom object dynamically
         */
        var img = document.createElement("img");

        /**
         * Get preview area of the image
         */
        var preview = $(imageContainer).find('tr.imagePreviewRow_'+i).find('td:first');

        /**
         * Append preview of selected image to the corresponding container
         */
        preview.append(img); 

        /**
         * Set style of appended preview(Can be done via css also)
         */
        preview.find('img').addClass('previewImage').css({'max-width': '500px', 'max-height': '500px'});

        /**
         * Initialize file reader
         */
        var reader = new FileReader();
        /**
         * Onload event of file reader assign target image to the preview
         */
        reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
        /**
         * Initiate read
         */
        reader.readAsDataURL(file);
    }
    /**
     * Show preview
     */
    $(imageContainer).show();
}

function remove_selected_image(close_button)
{
    /**
     * Remove this image from preview
     */
    var imageIndex = $(close_button).attr('imageindex');
    $(close_button).parents('.imagePreviewRow_' + imageIndex).remove();
}

function upload_images_selected(event, formObj)
{
    event.preventDefault();
    //Get number of images
    var imageCount = $('.previewImage').length;
    //Get all multi select inputs
    var fileInputs = document.querySelectorAll('.multipleImageFileInput');
    //Url where the image is to be uploaded
    var url= "/upload-directory/";
    //Get number of inputs
    var number_of_inputs = $(fileInputs).length; 
    var inputCount = 0;

    //Iterate through each file selector input
    $(fileInputs).each(function(index, input){

        fileList = input.files;
        // Create a new FormData object.
        var formData = new FormData();
        //Extra parameters can be added to the form data object
        formData.append('bulk_upload', '1');
        formData.append('username', $('input[name="username"]').val());
        //Iterate throug each images selected by each file selector and find if the image is present in the preview
        for (var i = 0; i < fileList.length; i++) {
            if ($(input).next('.imagePreviewTable').find('.imagePreviewRow_'+i).length != 0) {
                var file = fileList[i];
                // Check the file type.
                if (!file.type.match('image.*')) {
                    continue;
                }
                // Add the file to the request.
                formData.append('image_uploader_multiple[' +(inputCount++)+ ']', file, file.name);
            }
        }
        // Set up the request.
        var xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.onload = function () {
            if (xhr.status === 200) {
                var jsonResponse = JSON.parse(xhr.responseText);
                if (jsonResponse.status == 1) {
                    $(jsonResponse.file_info).each(function(){
                        //Iterate through response and find data corresponding to each file uploaded
                        var uploaded_file_name = this.original;
                        var saved_file_name = this.target;
                        var file_name_input = '<input type="hidden" class="image_name" name="image_names[]" value="' +saved_file_name+ '" />';
                        file_info_container.append(file_name_input);

                        imageCount--;
                    })
                    //Decrement count of inputs to find all images selected by all multi select are uploaded
                    number_of_inputs--;
                    if(number_of_inputs == 0) {
                        //All images selected by each file selector is uploaded
                        //Do necessary acteion post upload
                        $('.overlay').hide();
                    }
                } else {
                    if (typeof jsonResponse.error_field_name != 'undefined') {
                        //Do appropriate error action
                    } else {
                        alert(jsonResponse.message);
                    }
                    $('.overlay').hide();
                    event.preventDefault();
                    return false;
                }
            } else {
                /*alert('Something went wrong!');*/
                $('.overlay').hide();
                event.preventDefault();
            }
        };
        xhr.send(formData);
    })

    return false;
}

简单上载表单

<脚本>//表单提交$(“表单”).submit(函数(evt){evt.preventDefault();var formData=新的formData($(this)[0]);$.ajax美元({url:'fileUpload',类型:'POST',data:formData,异步:false,缓存:false,contentType:false,enctype:'多部分/表单数据',processData:false,成功:函数(响应){警报(响应);}});return false;});</script><!--上载表单--><表单><表><tr><td colspan=“2”>文件上载</td></tr><tr><th>选择文件</th><td><input id=“csv”name=“csv“type=“file”/></td></tr><tr><td colspan=“2”><input-type=“submit”value=“subject”/></td></tr></table></form>


我用简单的代码处理了这些问题。您可以从这里下载工作演示

就你的情况而言,这些都是可能的。我将逐步介绍如何使用AJAX jquery将文件上传到服务器。

首先让我们创建一个HTML文件,添加如下表单文件元素,如下所示。

<form action="" id="formContent" method="post" enctype="multipart/form-data" >
         <input  type="file" name="file"  required id="upload">
         <button class="submitI" >Upload Image</button> 
</form>

其次,创建一个jquery.js文件,并添加以下代码来处理向服务器提交的文件

    $("#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("file successfully submitted");
            },error: function(){
                alert("okey");
            }
         });
      });
    });

你完成了。查看更多信息


如果你想使用AJAX上传文件,这里是可以用于文件上传的代码。

$(document).ready(function() {
    var options = { 
                beforeSubmit:  showRequest,
        success:       showResponse,
        dataType: 'json' 
        }; 
    $('body').delegate('#image','change', function(){
        $('#upload').ajaxForm(options).submit();        
    }); 
});     
function showRequest(formData, jqForm, options) { 
    $("#validation-errors").hide().empty();
    $("#output").css('display','none');
    return true; 
} 
function showResponse(response, statusText, xhr, $form)  { 
    if(response.success == false)
    {
        var arr = response.errors;
        $.each(arr, function(index, value)
        {
            if (value.length != 0)
            {
                $("#validation-errors").append('<div class="alert alert-error"><strong>'+ value +'</strong><div>');
            }
        });
        $("#validation-errors").show();
    } else {
         $("#output").html("<img src='"+response.file+"' />");
         $("#output").css('display','block');
    }
}

这是用于上载文件的HTML

<form class="form-horizontal" id="upload" enctype="multipart/form-data" method="post" action="upload/image'" autocomplete="off">
    <input type="file" name="image" id="image" /> 
</form>

要上载用户使用jquery作为表单一部分提交的文件,请遵循以下代码:

var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);

然后将表单数据对象发送到服务器。

我们还可以将文件或Blob直接附加到FormData对象。

data.append("myfile", myBlob, "filename.txt");

要获取所有表单输入,包括type=“file”,需要使用FormData对象。提交表单后,您将能够在调试器->网络->标头中看到formData内容。

var url = "YOUR_URL";

var form = $('#YOUR_FORM_ID')[0];
var formData = new FormData(form);


$.ajax(url, {
    method: 'post',
    processData: false,
    contentType: false,
    data: formData
}).done(function(data){
    if (data.success){ 
        alert("Files uploaded");
    } else {
        alert("Error while uploading the files");
    }
}).fail(function(data){
    console.log(data);
    alert("Error while uploading the files");
});

<html>
    <head>
        <title>Ajax file upload</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
        <script>
            $(document).ready(function (e) {
            $("#uploadimage").on('submit', (function(e) {
            e.preventDefault();
                    $.ajax({
                    url: "upload.php", // Url to which the request is send
                            type: "POST", // Type of request to be send, called as method
                            data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
                            contentType: false, // The content type used when sending data to the server.
                            cache: false, // To unable request pages to be cached
                            processData:false, // To send DOMDocument or non processed data file it is set to false
                            success: function(data)   // A function to be called if request succeeds
                            {
                            alert(data);
                            }
                    });
            }));
        </script>
    </head>
    <body>
        <div class="main">
            <h1>Ajax Image Upload</h1><br/>
            <hr>
            <form id="uploadimage" action="" method="post" enctype="multipart/form-data">
                <div id="image_preview"><img id="previewing" src="noimage.png" /></div>
                <hr id="line">
                <div id="selectImage">
                    <label>Select Your Image</label><br/>
                    <input type="file" name="file" id="file" required />
                    <input type="submit" value="Upload" class="submit" />
                </div>
            </form>
        </div>
    </body>
</html>

var dataform = new FormData($("#myform")[0]);
//console.log(dataform);
$.ajax({
    url: 'url',
    type: 'POST',
    data: dataform,
    async: false,
    success: function(res) {
        response data;
    },
    cache: false,
    contentType: false,
    processData: false
});

如许多答案所示,使用FormData是一种方法。这里有一些代码非常适合这个目的。我也同意嵌套ajax块以完成复杂环境的意见。通过包括e.PreventDefault();根据我的经验,使代码更易于跨浏览器兼容。

    $('#UploadB1').click(function(e){        
    e.preventDefault();

    if (!fileupload.valid()) {
        return false;            
    }

    var myformData = new FormData();        
    myformData.append('file', $('#uploadFile')[0].files[0]);

    $("#UpdateMessage5").html("Uploading file ....");
    $("#UpdateMessage5").css("background","url(../include/images/loaderIcon.gif) no-repeat right");

    myformData.append('mode', 'fileUpload');
    myformData.append('myid', $('#myid').val());
    myformData.append('type', $('#fileType').val());
    //formData.append('myfile', file, file.name); 

    $.ajax({
        url: 'include/fetch.php',
        method: 'post',
        processData: false,
        contentType: false,
        cache: false,
        data: myformData,
        enctype: 'multipart/form-data',
        success: function(response){
            $("#UpdateMessage5").html(response); //.delay(2000).hide(1); 
            $("#UpdateMessage5").css("background","");

            console.log("file successfully submitted");
        },error: function(){
            console.log("not okay");
        }
    });
});

以下是我如何做到这一点:

HTML

<input type="file" id="file">
<button id='process-file-button'>Process</button>

JS

$('#process-file-button').on('click', function (e) {
    let files = new FormData(), // you can consider this as 'data bag'
        url = 'yourUrl';

    files.append('fileName', $('#file')[0].files[0]); // append selected file to the bag named 'file'

    $.ajax({
        type: 'post',
        url: url,
        processData: false,
        contentType: false,
        data: files,
        success: function (response) {
            console.log(response);
        },
        error: function (err) {
            console.log(err);
        }
    });
});

PHP

if (isset($_FILES) && !empty($_FILES)) {
    $file = $_FILES['fileName'];
    $name = $file['name'];
    $path = $file['tmp_name'];


    // process your file

}

2019年更新:

html

<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>

js

$(document).on('submit', '.fr', function(){

    $.ajax({ 
        type: 'post', 
        url: url, <--- you insert proper URL path to call your views.py function here.
        enctype: 'multipart/form-data',
        processData: false,
        contentType: false,
        data: new FormData(this) ,
        success: function(data) {
             console.log(data);
        }
        });
        return false;

    });

视图.py

form = ThisForm(request.POST, request.FILES)

if form.is_valid():
    text = form.cleaned_data.get("text")
    example_image = request.FILES['example_image']

使用纯js更容易

异步函数saveFile(inp){let formData=新formData();formData.append(“file”,inp.files[0]);wait-fetch('/upload/somedata',{method:“POST”,body:formData});警报(“成功”);}<input-type=“file”onchange=“saveFile(this)”>

在服务器端,您可以读取请求中自动包含的原始文件名(和其他信息)。您不需要将标题“Content-Type”设置为“multipart/form-data”。浏览器将自动设置它此解决方案应适用于所有主要浏览器。

下面是更详细的代码片段,包括错误处理、超时和额外的json发送

异步函数saveFile(inp){让用户={name:'john',年龄:34};let formData=新formData();let photo=inp.files[0];formData.append(“照片”,照片);formData.append(“用户”,JSON.stringify(用户));const ctrl=新建AbortController()//超时setTimeout(()=>ctrl.art(),50000);尝试{let r=等待获取('/upload/image',{method:“POST”,body:formData,signal:ctrl.signal});console.log('HTTP响应代码:',r.status);警报(“成功”);}捕获(e){console.log('休斯顿我们有问题…:',e);}}<input-type=“file”onchange=“saveFile(this)”><br><br>在选择文件之前,打开chrome控制台>网络选项卡以查看请求详细信息。<br><br><small>因为在本例中,我们将请求发送到https://stacksnippets.net/upload/image响应代码当然是404</小>


使用FormData。它工作得很好:-)。。。

var jform = new FormData();
jform.append('user',$('#user').val());
jform.append('image',$('#image').get(0).files[0]); // Here's the important bit

$.ajax({
    url: '/your-form-processing-page-url-here',
    type: 'POST',
    data: jform,
    dataType: 'json',
    mimeType: 'multipart/form-data', // this too
    contentType: false,
    cache: false,
    processData: false,
    success: function(data, status, jqXHR){
        alert('Hooray! All is well.');
        console.log(data);
        console.log(status);
        console.log(jqXHR);

    },
    error: function(jqXHR,status,error){
        // Hopefully we should never reach here
        console.log(jqXHR);
        console.log(status);
        console.log(error);
    }
});

$(“#form id”).submit(函数(e){e.预防违约();});$(“#form id”).submit(函数(e){var formObj=$(此);var formURL=formObj.attr(“操作”);var formData=新的formData(this);$.ajax美元({url:formURL,类型:'POST',data:formData,processData:false,contentType:false,异步:true,缓存:false,enctype:“multipart/form data”,dataType:“json”,成功:函数(数据){if(data.success){警报(data.success)} if(data.error){警报(data.error)} }});});<script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js“></script><form class=“form horizontal”id=“form id”action=“masterFileController”enctype=“multipart/form data”><button class=“btn success btn”type=“submit”id=“btn save”>提交</button></form>

servlet响应为“out.print(“您的响应”);”


<input class="form-control cu-b-border" type="file" id="formFile">
<img id="myImg" src="#">

在js中

<script>
    var formData = new FormData();
    formData.append('file', $('#formFile')[0].files[0]);
    $.ajax({
        type: "POST",
        url: '/GetData/UploadImage',
        data: formData,
        processData: false, // tell jQuery not to process the data
        contentType: false, // tell jQuery not to set contentType
        success: function (data) {
            console.log(data);
            $('#myImg').attr('src', data);
        },
        error: function (xhr, ajaxOptions, thrownError) {
        }
    })
</script>

在控制器中

public ActionResult UploadImage(HttpPostedFileBase file)
        {
            string filePath = "";
            if (file != null)
            {
                string path = "/uploads/Temp/";
                if (!Directory.Exists(Server.MapPath("~" + path)))
                {
                    Directory.CreateDirectory(Server.MapPath("~" + path));
                }
                filePath = FileUpload.SaveUploadedFile(file, path);
            }
            
            return Json(filePath, JsonRequestBehavior.AllowGet);
        }

这是我的代码

var formData = new FormData();
var files = $('input[type=file]');
for (var i = 0; i < files.length; i++) {
if (files[i].value == "" || files[i].value == null) {
 return false;
}
else {
 formData.append(files[i].name, files[i].files[0]);
}
}
var formSerializeArray = $("#Form").serializeArray();
for (var i = 0; i < formSerializeArray.length; i++) {
  formData.append(formSerializeArray[i].name, formSerializeArray[i].value)
}
$.ajax({
 type: 'POST',
 data: formData,
 contentType: false,
 processData: false,
 cache: false,
 url: '/Controller/Action',
 success: function (response) {
 if (response.Success == true) {
    return true;
 }
 else {
    return false;
 }
 },
 error: function () {
   return false;
 },
 failure: function () {
   return false;
 }
 });