jQuery Ajax File Upload
我可以使用下面的jquery代码使用ajax请求的post方法执行文件上传吗?
1 2 3 4 5 6 7 8 9 10 | $.ajax({ type:"POST", timeout: 50000, url: url, data: dataString, success: function (data) { alert('success'); return false; } }); |
如果可能,我需要填写"数据"部分吗?这是正确的方法吗?我只将文件发布到服务器端。
我一直在谷歌搜索,但我发现的是一个插件,而在我的计划中,我不想使用它。至少目前如此。
通过Ajax可以上传文件。您可以上传文件,而不必使用iframe刷新页面。您可以在这里查看更多详细信息
更新:
XHR2支持通过Ajax上传文件。例如,通过FormData对象,但不幸的是,所有/旧浏览器都不支持它。
FormData支持从以下桌面浏览器版本开始。IE 10 +,火狐4 +,铬7 +,Safari 5 +,歌剧12 +
有关详细信息,请参见MDN链接
通过Ajax上传文件不再需要iframes。我最近自己做的。查看这些页面:
在Ajax和jQuery中使用HTML5文件上载
http://dev.w3.org/2006/webapi/fileapi/文件阅读器界面
更新了答案并进行了清理。使用getSize函数检查大小,或使用getType函数检查类型。添加了ProgressBar HTML和CSS代码。
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 47 48 49 50 51 52 53 54 55 56 57 58 | 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 +"%"); }; |
如何使用上载类
1 2 3 4 5 6 7 8 9 10 | //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代码
1 | 0% |
ProgressBar CSS代码
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 | #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; } |
Ajax发布和上传文件是可能的。我正在使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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对象,空的还是从(序列化的)创建的?-
以下是详细信息:-如何使用jquery.ajax和formdata上载文件-通过jquery上传文件,提供对象formdata,没有文件名,get请求
对于php进程,可以使用如下内容:
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 | //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 )); } |
简单上载表单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | //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; }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!--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> |
我已经很晚了,但我在寻找一个基于Ajax的图像上传解决方案,我所寻找的答案在这篇文章中有点零散。我解决的解决方案涉及到FormData对象。我组装了一个基本的代码形式。您可以看到它演示了如何使用fd.append()向表单添加自定义字段,以及如何在Ajax请求完成时处理响应数据。
上传HTML:
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 | <!DOCTYPE html> <html> <head> Image Upload Form <script src="//code.jquery.com/jquery-1.9.1.js"> <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; } </head> <body> <form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();"> <label>Select a file:</label> <input type="file" name="file" required /> <input type="submit" value="Upload" /> </form> </body> </html> |
在使用PHP的情况下,这里提供了一种处理上载的方法,其中包括使用上面HTML中演示的两个自定义字段。
上传文件
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 | <?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"] .""; } else { $filename = $label.$_FILES["file"]["name"]; echo"Upload:" . $_FILES["file"]["name"] .""; echo"Type:" . $_FILES["file"]["type"] .""; echo"Size:" . ($_FILES["file"]["size"] / 1024) ." kB"; echo"Temp file:" . $_FILES["file"]["tmp_name"] .""; 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"; } ?> |
使用xmlhttpRequest()确实可以上载Ajax。不需要iframes。可以显示上载进度。
有关详细信息,请参阅:回答https://stackoverflow.com/a/4943774/873282以询问jquery上载进度和Ajax文件上载。
如果你想这样做:
1 2 3 4 5 6 7 8 9 10 11 12 13 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'); }); |
比
https://github.com/lgersman/jquery.orangevolt-ampe/blob/master/src/jquery.upload.js网站
可能是你的解决方案。
- 使用隐藏的iframe并将表单目标设置为该iframe的名称。这样,提交表单时,只刷新iframe。
- 为iframe的load事件注册一个事件处理程序来分析响应。
有关我的博客文章的更多详细信息:http://blog.manki.in/2011/08/ajax-fie-upload.html。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $("#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; }); |
编辑:注意内容类型和处理数据您可以简单地使用它通过Ajax上传文件……提交输入不能在表单元素()之外。
我是这样工作的:
HTML
1 2 | <input type="file" id="file"> <button id='process-file-button'>Process</button> |
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $('#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
1 2 3 4 5 6 7 8 9 | if (isset($_FILES) && !empty($_FILES)) { $file = $_FILES['fileName']; $name = $file['name']; $path = $file['tmp_name']; // process your file } |
在通过Ajax从预览中删除不需要的文件后,我实现了一个具有即时预览和上传功能的多文件选择。
有关详细文档,请访问:http://anascocoder.blogspot.ae/2014/12/multi-file-select-preview-without.html
演示:http://jsfiddle.net/anas/6v8kz/7/embedded/result/
jfiddle:http://jsfiddle.net/anas/6v8kz/7/
Javascript:
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 | $(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; } |
我用一个简单的代码处理了这些问题。你可以从这里下载一个工作演示
对于你的情况,这些是很有可能的。我将逐步介绍如何使用Ajax jQuery将文件上载到服务器。
首先,我们创建一个HTML文件来添加如下表单文件元素,如下所示。
1 2 3 4 | <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文件并添加以下代码以处理我们向服务器提交的文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | $("#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"); } }); }); }); |
完成了。查看更多
使用formdata是许多答案所指出的方法。这里有一些代码对于这个目的非常有用。我也同意嵌套Ajax块以完成复杂情况的注释。通过包括e.preventDefault();根据我的经验,使代码更加兼容跨浏览器。
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 | $('#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"); } }); }); |
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 | <html> <head> Ajax file upload <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> $(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); } }); })); </head> <body> Ajax Image Upload<br/> <form id="uploadimage" action="" method="post" enctype="multipart/form-data"> <img id="previewing" src="noimage.png" /> <hr id="line"> <label>Select Your Image</label><br/> <input type="file" name="file" id="file" required /> <input type="submit" value="Upload" class="submit" /> </form> </body> </html> |
可以,只需使用javascript获取文件,确保将文件作为数据URL读取。解析base64之前的内容以实际获取base64编码的数据,然后如果您使用的是PHP或任何后端语言,则可以解码base64数据并保存到如下所示的文件中
1 2 3 4 5 6 7 8 9 10 11 12 | 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"])); |
当然,您可能需要做一些验证,比如检查您要处理的文件类型和类似的事情,但这是一个想法。
您可以使用方法ajaxsubmit,如下所示:)选择需要上载到服务器的文件时,表单将提交到服务器:)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $(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; }); }); |
要上传用户使用jquery作为表单一部分提交的文件,请遵循以下代码:
1 2 | var formData = new FormData(); formData.append("userfile", fileInputElement.files[0]); |
然后将表单数据对象发送到服务器。
我们还可以将文件或BLOB直接附加到FormData对象。
1 | data.append("myfile", myBlob,"filename.txt"); |
如果你想使用Ajax上传文件,这里有一些代码可以用来上传文件。
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 | $(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(''+ value +''); } }); $("#validation-errors").show(); } else { $("#output").html("<img src='"+response.file+"' />"); $("#output").css('display','block'); } } |
这是上传文件的HTML
1 2 3 | <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> |
要获取所有表单输入,包括type="file",需要使用FormData对象。提交表单后,您将能够在调试器->网络->头中看到表单数据内容。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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"); }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 }); |
2019更新:
HTML
1 2 3 4 5 | <form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %} <textarea name='text'> <input name='example_image'> <button type="submit"> </form> |
JS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $(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; }); |
VIEW
1 2 3 4 5 | form = ThisForm(request.POST, request.FILES) if form.is_valid(): text = form.cleaned_data.get("text") example_image = request.FILES['example_image'] |
我想到了一个想法:
1 | Have an iframe on page and have a referencer. |
有一个将input:file元素移动到的表单。
1 | Form: A processing page AND a target of the FRAME. |
结果将发布到帧,然后您只需将提取的数据向上发送到所需的图像标记,如下所示:
1 | data:image/png;base64,asdfasdfasdfasdfa |
页面加载。
我相信它对我有用,而且取决于你可能会做如下的事情:
1 2 3 | .aftersubmit(function(){ stopPropigation()// or some other code which would prevent a refresh. }); |