jQuery Ajax文件上传

Wil*_*lly 722 javascript ajax jquery post file-upload

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

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

如果可能,我是否需要填写"数据"部分?这是正确的方法吗?我只将文件发布到服务器端.

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

Ade*_*eel 584

文件上传是不是可以通过Ajax.您可以使用IFrame上传文件,而无需刷新页面.你可以在这里查看更多细节

更新:

使用XHR2,支持通过AJAX上传文件.例如,通过FormData对象,但不幸的是,所有/旧浏览器都不支持它.

FormData支持从以下桌面浏览器版本开始.IE 10 +,Firefox 4.0 +,Chrome 7 +,Safari 5 +,Opera 12+

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

  • 具体来说,IE <10不会,因为那些懒得阅读链接的人. (146认同)
  • 以下是不支持的特定浏览器列表:http://caniuse.com/#search=FormData此外我还没有测试过这个,但这里是FormData的polyfill https://gist.github.com/3120320 (41认同)
  • @DrewCalder大多数IE用户都是办公室工作人员,由于公司政策的原因,他们无法选择使用哪种浏览器.我不认为年龄与它有很大关系.我猜大多数人> 70让他们的后代安装Chrome或FF而不是:) (29认同)
  • @Synexis不,我们不必再等那么久了,因为所有的IE在全球市场占有率仅为22%,在美国市场占有率为27%,并且下降速度很快.有可能是70岁以上的人.因此,IE决定开发人员必须做什么,IE要么必须塑造或退出竞争. (18认同)
  • [这个链接](http://blog.teamtreehouse.com/uploading-files-ajax)真的帮助我理解最低限度.我没有必要使用xhr请求.如果你确实使用ajax,请确保将`enctype`设置为``form/multipart"`! (3认同)

Zii*_*der 302

通过ajax上传文件不再需要iframe.我最近自己做了.看看这些页面:

使用带有AJAX和jQuery的HTML5文件上传

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

更新了答案并进行了清理.使用getSize函数检查大小或使用getType函数检查类型.添加了进度条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 + "%");
};
Run Code Online (Sandbox Code Playgroud)

如何使用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();
});
Run Code Online (Sandbox Code Playgroud)

Progressbar html代码

<div id="progress-wrp">
    <div class="progress-bar"></div>
    <div class="status">0%</div>
</div>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

  • 我不认为我们可以像@Ziinloader那样使用它.你正在使用一些不包括的本地方法:`writer(catchFile)`.什么是`writer()`? (8认同)
  • 请注意,myXhr似乎是全局的以及名称,大小和类型.另外,最好使用"beforeSend"来扩充已经创建的XMLHttpRequest对象,而不是使用"xhr"创建一个然后更改它. (4认同)
  • 您可以或多或少地直接复制代码并使用它.只需更改一些id名称和类名.任何保管都是您自己的. (3认同)
  • 如果数据还包含少量字段以及要上载的文件,该怎么办? (3认同)
  • @user428747这是已知的,但这不是这段代码的问题,这是IE方面的技术限制(就像总是TBH一样)。http://caniuse.com/#feat=xhr2 (2认同)
  • @Ziinloader这是一个非常有用的例子,我看到你已经回来并多次维护了.真正的答案远远超过我能给予的一个支持. (2认同)
  • *$(this)[0]* 是*这个* (2认同)

小智 183

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);
       }
});
Run Code Online (Sandbox Code Playgroud)

如您所见,您必须创建一个FormData对象,空或从(序列化? - $('#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
            ));
}
Run Code Online (Sandbox Code Playgroud)

  • `formData.append('file',$('#file')[0] .files [0]);`返回`undefined`和`console.log(formData)`除了`_proto_`之外什么都没有 (5认同)
  • 我需要引用什么jquery库来运行此代码? (2认同)
  • 我得到了这个工作......捏我,我在jQuery Ajax文件上传天堂!`var formData = new FormData(); formData.append('file',document.getElementById('file').files [0]); $ .ajax({url:$("form [name ='uploadPhoto']").attr("action"),type:'POST',data:formData,processData:false,//告诉jQuery不要处理data contentType:false,//告诉jQuery不要设置contentType成功:function(data){console.log(data); alert(data);}});` (2认同)
  • @RaymondWachaga 这是编码类型,而不是加密类型。:) (2认同)
  • 我真的很挣扎……经过几个小时的研究等,我发现这确实有帮助。谢了哥们!你的解决方案的第一部分对我来说就像一个魅力。这正是我所需要的:-) (2认同)

vic*_*sys 99

简单上传表格

 <script>
   //form Submit
   $("form").submit(function(evt){	 
      evt.preventDefault();
      var formData = new FormData($(this)[0]);
   $.ajax({
       url: 'fileUpload',
       type: 'POST',
       data: formData,
       async: false,
       cache: false,
       contentType: false,
       enctype: 'multipart/form-data',
       processData: false,
       success: function (response) {
         alert(response);
       }
   });
   return false;
 });
</script>
Run Code Online (Sandbox Code Playgroud)
<!--Upload Form-->
<form>
  <table>
    <tr>
      <td colspan="2">File Upload</td>
    </tr>
    <tr>
      <th>Select File </th>
      <td><input id="csv" name="csv" type="file" /></td>
    </tr>
    <tr>
      <td colspan="2">
        <input type="submit" value="submit"/> 
      </td>
    </tr>
  </table>
</form>
Run Code Online (Sandbox Code Playgroud)

  • *$(this)[0]*是*这* (17认同)
  • 服务器上发布文件的参数是什么?能否请您发布服务器部分。 (2认同)

lee*_*8oi 67

我为此迟到了,但我正在寻找一个基于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>
Run Code Online (Sandbox Code Playgroud)

如果您正在使用php,这是一种处理上传的方法,其中包括使用上述html中演示的两个自定义字段.

upload.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";
}
?>
Run Code Online (Sandbox Code Playgroud)

  • @HogRider - 如果你谷歌你的错误信息,这是第一个结果:http://stackoverflow.com/questions/10752055/cross-origin-requests-are-only-supported-for-http-error-when-loading- a-local您是通过`file://`在本地访问您的网页,而不是使用Web服务器?顺便说一句,在没有先了解代码的情况下,盲目地复制和粘贴代码并不是最好的做法.我建议你逐行完成代码,以便在使用代码之前了解正在发生的事情. (2认同)

kop*_*por 31

使用XMLHttpRequest()确实可以上传AJAX.没有必要的iframe.可以显示上传进度.

有关详细信息,请参阅:回答/sf/answers/346064211/以质疑jQuery上载进度和AJAX文件上载.

  • 不幸的是IE <10不支持这一点. (23认同)

Kam*_*ski 19

使用纯js更容易

async function saveFile(inp) 
{
    let formData = new FormData();           
    formData.append("file", inp.files[0]);
    await fetch('/upload/somedata', {method: "POST", body: formData});    
    alert('success');
}
Run Code Online (Sandbox Code Playgroud)
<input type="file" onchange="saveFile(this)" >
Run Code Online (Sandbox Code Playgroud)

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

这是带有错误处理、超时和额外 json 发送的更多开发片段

async function saveFile(inp) 
{
    let user = { name:'john', age:34 };
    let formData = new FormData();
    let photo = inp.files[0];      
         
    formData.append("photo", photo);
    formData.append("user", JSON.stringify(user));  
    
    const ctrl = new AbortController() // timeout
    setTimeout(() => ctrl.abort(), 50000);

    try {
       let r = await fetch('/upload/image', 
         {method: "POST", body: formData, signal: ctrl.signal}); 
       console.log('HTTP response code:',r.status); 
       alert('success');
    } catch(e) {
       console.log('Huston we have problem...:', e);
    }
    
}
Run Code Online (Sandbox Code Playgroud)
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
Run Code Online (Sandbox Code Playgroud)


del*_*8uk 16

使用表单数据。它工作得很好:-) ...

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);
    }
});
Run Code Online (Sandbox Code Playgroud)


М.Б*_*.Б. 15

这是我如何工作:

HTML

<input type="file" id="file">
<button id='process-file-button'>Process</button>
Run Code Online (Sandbox Code Playgroud)

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);
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

PHP

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


    // process your file

}
Run Code Online (Sandbox Code Playgroud)

  • 对此最有帮助的是$('#file')[0] .files [0]`,这是某种奇怪的JS解决方法,不需要适当的&lt;form&gt; (2认同)
  • 这是完整的解决方案,PHP 位也有帮助。 (2认同)

lge*_*man 14

如果您想这样做:

$.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');                    
});
Run Code Online (Sandbox Code Playgroud)

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

可能是你的解决方案.

  • 谢谢你发布你的答案!请务必仔细阅读[自我推广常见问题解答](http://stackoverflow.com/faq#promotion).另请注意,每次链接到您自己的网站/产品时,您都要*免费发布免责声明. (2认同)

Man*_*nki 13

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

有关我博客文章的更多详情:http://blog.manki.in/2011/08/ajax-fie-upload.html.


Gvi*_*ice 12

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

编辑:注意内容类型和过程数据你可以简单地使用这个来通过Ajax上传文件......提交输入不能是外部表单元素:)

  • 使用此方法,您可以发布表单,但不能使用"文件"类型字段.这个问题具体是关于文件上传. (3认同)

Jay*_*Jay 10

2019更新:

html

<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>
Run Code Online (Sandbox Code Playgroud)

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;

    });
Run Code Online (Sandbox Code Playgroud)

views.py

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

if form.is_valid():
    text = form.cleaned_data.get("text")
    example_image = request.FILES['example_image']
Run Code Online (Sandbox Code Playgroud)

  • 因为在使用Django时,该问题的可比性很明显,而且如果您使用的是Django,则在解决该问题方面没有太多指导。我以为我会提供主动帮助,以防万一有人像我将来那样来到这里。有一个艰难的一天? (6认同)
  • 这如何改善已经给出的任何答案?此答案还提到了一个 views.py 文件,该文件是 Django,与该问题无关。 (3认同)

Dav*_*vid 8

要获取所有表单输入,包括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");
});
Run Code Online (Sandbox Code Playgroud)


Ima*_*Ima 7

我通过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/

使用Javascript:

    $(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;
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*syo 7

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

对于您的情况,这些非常可能.我将逐步介绍如何使用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>
Run Code Online (Sandbox Code Playgroud)

其次创建一个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");
            }
         });
      });
    });
Run Code Online (Sandbox Code Playgroud)

你完成了.查看更多


小智 7

要上传用户使用 jquery 作为表单一部分提交的文件,请按照以下代码操作:

var formData = new FormData();
formData.append("userfile", fileInputElement.files[0]);
Run Code Online (Sandbox Code Playgroud)

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

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

data.append("myfile", myBlob, "filename.txt");
Run Code Online (Sandbox Code Playgroud)


Quy*_* Le 6

您可以使用 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;
});
});
Run Code Online (Sandbox Code Playgroud)

  • 我相信你在谈论 jquery [form](https://github.com/malsup/form) 插件。除了您的答案中缺少细节之外,这确实是这里的最佳选择。 (2认同)

Pia*_*nti 6

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

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"]));
Run Code Online (Sandbox Code Playgroud)

当然,您可能需要进行一些验证,例如检查您要处理的文件类型以及类似的内容,但这就是这个主意。


Mik*_*mar 6

使用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");
        }
    });
});
Run Code Online (Sandbox Code Playgroud)


Nik*_* K. 5

如果您想使用 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');
    }
}
Run Code Online (Sandbox Code Playgroud)

这是上传文件的 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>
Run Code Online (Sandbox Code Playgroud)


Nik*_*iya 5

<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>
Run Code Online (Sandbox Code Playgroud)