Ser*_*Amo 2841 javascript ajax jquery asynchronous xmlhttprequest
我想用jQuery异步上传一个文件.这是我的HTML:
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>
Run Code Online (Sandbox Code Playgroud)
在这里我的__CODE__代码:
$(document).ready(function () {
$("#uploadbutton").click(function () {
var filename = $("#file").val();
$.ajax({
type: "POST",
url: "addFile.do",
enctype: 'multipart/form-data',
data: {
file: filename
},
success: function () {
alert("Data Uploaded: ");
}
});
});
});
Run Code Online (Sandbox Code Playgroud)
我只获取文件名,而不是上传文件.我该怎么做才能解决这个问题?
我正在使用jQuery Form Plugin上传文件.
ola*_*nod 2482
使用HTML5,您可以使用Ajax和jQuery进行文件上传.不仅如此,您还可以使用HTML5进度标记(或div)执行文件验证(名称,大小和MIME类型)或处理progress事件.最近我不得不制作一个文件上传器,但我不想使用Flash或iframe或插件,经过一些研究后我想出了解决方案.
HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
Run Code Online (Sandbox Code Playgroud)
首先,如果需要,您可以进行一些验证.例如,在文件的onChange事件中:
$(':file').on('change', function () {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k');
}
// Also see .name, .type
});
Run Code Online (Sandbox Code Playgroud)
现在,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;
}
});
});
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,使用HTML5(以及一些研究)文件上传不仅可以实现,而且非常简单.尝试使用谷歌浏览器,因为每个浏览器都没有这些示例的HTML5组件.
Oli*_*Oli 267
使用"新"HTML5 fileAPI 要理解的重要一点是,直到IE 10才支持.如果您所针对的特定市场对旧版Windows的倾向高于平均水平,那么您可能无法访问它.
截至2017年,大约5%的浏览器是IE 6,7,8或9中的一个.如果你进入一家大公司(例如,这是一个B2B工具,或者你正在提供培训的东西),那么这个数字可能会爆炸.2016年,我与超过60%的机器使用IE8的公司打交道.
这是编辑的2019年,距我最初的答案差不多11年.IE9及更低版本在全球范围内均在1%左右,但仍然存在较高使用率的集群.
从这个重要的外卖-whatever的特征-是检查什么的浏览器的用户使用.如果你不这样做,你将学到一个快速而痛苦的教训,为什么"为我工作"对于客户的交付是不够的.caniuse是一个有用的工具,但请注意他们从中获取人口统计数据的位置.它们可能与您的不一致.这绝不比企业环境更真实.
我的答案是从2008年开始的.
但是,有一些可行的非JS文件上传方法.您可以在页面上创建一个iframe(使用CSS隐藏),然后定位表单以发布到该iframe.主页不需要移动.
这是一个"真实"的帖子,所以它不是完全互动的.如果您需要状态,则需要服务器端进行处理.这会根据您的服务器而有很大差异.ASP.NET具有更好的机制.PHP plain失败,但您可以使用Perl或Apache修改来绕过它.
如果您需要多个文件上传,最好一次执行一个文件(以克服最大文件上载限制).将第一个表单发布到iframe,使用上面的内容监控其进度,完成后,将第二个表单发布到iframe,依此类推.
或者使用Java/Flash解决方案.他们对帖子的处理方式更加灵活......
小智 110
我建议使用Fine Uploader插件来实现此目的.你的JavaScript代码是:
$(document).ready(function() {
$("#uploadbutton").jsupload({
action: "addFile.do",
onComplete: function(response){
alert( "server response: " + response);
}
});
});
Run Code Online (Sandbox Code Playgroud)
Mat*_*ias 99
注意:此答案已过时,现在可以使用XHR上传文件.
您无法使用XMLHttpRequest(Ajax)上传文件.您可以使用iframe或Flash模拟效果.优秀的jQuery表单插件,通过iframe发布您的文件以获得效果.
404*_*404 91
为未来的读者做好准备.
如果支持FormData和File API(HTML5功能),您可以使用该方法使用jQuery上传文件.$.ajax()
您也可以在没有FormData的情况下发送文件,但无论是哪种方式都必须存在File API来处理文件,以便可以使用XMLHttpRequest(Ajax)发送文件.
$.ajax({
url: 'file/destination.html',
type: 'POST',
data: new FormData($('#formWithFiles')[0]), // The form with the file inputs.
processData: false,
contentType: false // Using FormData, no need to process data.
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
Run Code Online (Sandbox Code Playgroud)
有关快速,纯JavaScript(无jQuery)示例,请参阅" 使用FormData对象发送文件 ".
当不支持HTML5(没有File API)时,唯一的其他纯JavaScript解决方案(没有Flash或任何其他浏览器插件)是隐藏的iframe技术,它允许在不使用XMLHttpRequest对象的情况下模拟异步请求.
它包括将iframe设置为带有文件输入的表单的目标.当用户提交请求并上传文件但响应显示在iframe内部而不是重新呈现主页面时.隐藏iframe使整个过程对用户透明并模拟异步请求.
如果操作正确,它应该在任何浏览器上虚拟工作,但它有一些警告如何从iframe获取响应.
在这种情况下,您可能更喜欢使用像Bifröst这样的包装器插件,它使用iframe技术,但也提供了一个jQuery Ajax传输,允许使用如下方法发送文件$.ajax():
$.ajax({
url: 'file/destination.html',
type: 'POST',
// Set the transport to use (iframe means to use Bifröst)
// and the expected data type (json in this case).
dataType: 'iframe json',
fileInputs: $('input[type="file"]'), // The file inputs containing the files to send.
data: { msg: 'Some extra data you might need.'}
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
Run Code Online (Sandbox Code Playgroud)
Bifröst只是一个小包装器,它为jQuery的ajax方法添加了后备支持,但许多上述插件如jQuery Form Plugin或jQuery File Upload包括从HTML5到不同后备的整个堆栈以及一些有用的功能来简化过程.根据您的需求和要求,您可能需要考虑裸实现或此插件中的任何一个.
Jor*_*ein 84
这个AJAX文件上传jQuery插件上传文件somehwere,并将响应传递给回调,没有别的.
<input type="file">- 使用尽可能少 -
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
Run Code Online (Sandbox Code Playgroud)
- 或者多 -
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
Run Code Online (Sandbox Code Playgroud)
Tec*_*hie 60
我一直在使用下面的脚本来上传恰好工作的图像.
<input id="file" type="file" name="file"/>
<div id="response"></div>
Run Code Online (Sandbox Code Playgroud)
jQuery('document').ready(function(){
var input = document.getElementById("file");
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("image", file);
formdata.append("extra",'extra-data');
}
if (formdata) {
jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
jQuery.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
jQuery('div#response').html("Successfully uploaded");
}
});
}
}
else
{
alert('Not a vaild image!');
}
}
}, false);
});
Run Code Online (Sandbox Code Playgroud)
div上传完成后,我使用响应来显示上传动画和响应.
最好的部分是,当您使用此脚本时,您可以使用该文件发送额外的数据,如ids等.我extra-data在剧本中提到过它.
在PHP级别,这将作为普通文件上载.额外数据可以作为$_POST数据检索.
在这里,你没有使用插件和东西.您可以根据需要更改代码.你不是在这里盲目编码.这是任何jQuery文件上传的核心功能.实际上是Javascript.
mpe*_*pen 47
你可以很容易地在vanilla 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);
Run Code Online (Sandbox Code Playgroud)
Zay*_*Ali 46
您可以使用jQuery上传.ajax().
HTML:
<form id="upload-form">
<div>
<label for="file">File:</label>
<input type="file" id="file" name="file" />
<progress class="progress" value="0" max="100"></progress>
</div>
<hr />
<input type="submit" value="Submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
CSS
.progress { display: none; }
Run Code Online (Sandbox Code Playgroud)
使用Javascript:
$(document).ready(function(ev) {
$("#upload-form").on('submit', (function(ev) {
ev.preventDefault();
$.ajax({
xhr: function() {
var progress = $('.progress'),
xhr = $.ajaxSettings.xhr();
progress.show();
xhr.upload.onprogress = function(ev) {
if (ev.lengthComputable) {
var percentComplete = parseInt((ev.loaded / ev.total) * 100);
progress.val(percentComplete);
if (percentComplete === 100) {
progress.hide().val(0);
}
}
};
return xhr;
},
url: 'upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(data, status, xhr) {
// ...
},
error: function(xhr, status, error) {
// ...
}
});
}));
});
Run Code Online (Sandbox Code Playgroud)
Art*_*nix 43
我过去做过的最简单,最健壮的方法是简单地使用您的表单定位隐藏的iFrame标记 - 然后它将在iframe中提交而不重新加载页面.
也就是说,如果您不想使用插件,JavaScript或除HTML之外的任何其他形式的"魔术".当然你可以将它与JavaScript或者你有什么相结合......
<form target="iframe" action="" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<iframe name="iframe" id="iframe" style="display:none" ></iframe>
Run Code Online (Sandbox Code Playgroud)
您还可以读取iframe的内容以onLoad获取服务器错误或成功响应,然后将其输出给用户.
Chrome,iFrame和onLoad
- 注意 - 如果您对上传/下载时如何设置UI阻止程序感兴趣,则只需继续阅读
目前,当用于传输文件时,Chrome不会触发iframe的onLoad事件.Firefox,IE和Edge都会激活onload事件以进行文件传输.
我发现Chrome的唯一解决方案是使用cookie.
基本上在上传/下载开始时这样做:
使用cookie是很难看的,但它确实有效.
我下载了一个jQuery插件来处理Chrome的这个问题,你可以在这里找到
https://github.com/ArtisticPhoenix/jQuery-Plugins/blob/master/iDownloader.js
同样的基本原则也适用于上传.
要使用下载器(显然包括JS)
$('body').iDownloader({
"onComplete" : function(){
$('#uiBlocker').css('display', 'none'); //hide ui blocker on complete
}
});
$('somebuttion').click( function(){
$('#uiBlocker').css('display', 'block'); //block the UI
$('body').iDownloader('download', 'htttp://example.com/location/of/download');
});
Run Code Online (Sandbox Code Playgroud)
在服务器端,在传输文件数据之前,创建cookie
setcookie('iDownloader', true, time() + 30, "/");
Run Code Online (Sandbox Code Playgroud)
该插件将看到cookie,然后触发onComplete回调.
wbh*_*ing 32
我在Rails环境中编写了这个.如果你使用轻量级的jQuery-form插件,它只有大约五行JavaScript.
挑战在于使AJAX上传工作,因为标准remote_form_for不了解多部分表单提交.它不会发送文件数据Rails通过AJAX请求回寻.
这就是jQuery-form插件发挥作用的地方.
这是它的Rails代码:
<% remote_form_for(:image_form,
:url => { :controller => "blogs", :action => :create_asset },
:html => { :method => :post,
:id => 'uploadForm', :multipart => true })
do |f| %>
Upload a file: <%= f.file_field :uploaded_data %>
<% end %>
Run Code Online (Sandbox Code Playgroud)
这是相关的JavaScript:
$('#uploadForm input').change(function(){
$(this).parent().ajaxSubmit({
beforeSubmit: function(a,f,o) {
o.dataType = 'json';
},
complete: function(XMLHttpRequest, textStatus) {
// XMLHttpRequest.responseText will contain the URL of the uploaded image.
// Put it in an image element you create, or do with it what you will.
// For example, if you have an image elemtn with id "my_image", then
// $('#my_image').attr('src', XMLHttpRequest.responseText);
// Will set that image tag to display the uploaded image.
},
});
});
Run Code Online (Sandbox Code Playgroud)
这是Rails控制器动作,非常香草:
@image = Image.new(params[:image_form])
@image.save
render :text => @image.public_filename
Run Code Online (Sandbox Code Playgroud)
过去几周我一直在使用Bloggity,它就像一个冠军.
use*_*949 31
简单的Ajax Uploader是另一种选择:
https://github.com/LPology/Simple-Ajax-Uploader
用法示例:
var uploader = new ss.SimpleUpload({
button: $('#uploadBtn'), // upload button
url: '/uploadhandler', // URL of server-side upload handler
name: 'userfile', // parameter name of the uploaded file
onSubmit: function() {
this.setProgressBar( $('#progressBar') ); // designate elem as our progress bar
},
onComplete: function(file, response) {
// do whatever after upload is finished
}
});
Run Code Online (Sandbox Code Playgroud)
小智 24
jQuery Uploadify是我之前用来上传文件的另一个好插件.JavaScript代码与以下内容一样简单:代码.但是,新版本在Internet Explorer中不起作用.
$('#file_upload').uploadify({
'swf': '/public/js/uploadify.swf',
'uploader': '/Upload.ashx?formGuid=' + $('#formGuid').val(),
'cancelImg': '/public/images/uploadify-cancel.png',
'multi': true,
'onQueueComplete': function (queueData) {
// ...
},
'onUploadStart': function (file) {
// ...
}
});
Run Code Online (Sandbox Code Playgroud)
我已经做了很多搜索,我已经找到了另一个没有任何插件上传文件的解决方案,只有ajax.解决方案如下:
$(document).ready(function () {
$('#btn_Upload').live('click', AjaxFileUpload);
});
function AjaxFileUpload() {
var fileInput = document.getElementById("#Uploader");
var file = fileInput.files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'Uploader.ashx');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert('success');
}
else if (uploadResult == 'success')
alert('error');
};
xhr.send(fd);
}
Run Code Online (Sandbox Code Playgroud)
Sid*_*ury 23
这里是另一个如何上传文件的解决方案(没有任何插件)
使用简单的Javascripts和AJAX(带进度条)
HTML部分
<form id="upload_form" enctype="multipart/form-data" method="post">
<input type="file" name="file1" id="file1"><br>
<input type="button" value="Upload File" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<h3 id="status"></h3>
<p id="loaded_n_total"></p>
</form>
Run Code Online (Sandbox Code Playgroud)
JS部分
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("file1").files[0];
// alert(file.name+" | "+file.size+" | "+file.type);
var formdata = new FormData();
formdata.append("file1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "file_upload_parser.php");
ajax.send(formdata);
}
function progressHandler(event){
_("loaded_n_total").innerHTML = "Uploaded "+event.loaded+" bytes of "+event.total;
var percent = (event.loaded / event.total) * 100;
_("progressBar").value = Math.round(percent);
_("status").innerHTML = Math.round(percent)+"% uploaded... please wait";
}
function completeHandler(event){
_("status").innerHTML = event.target.responseText;
_("progressBar").value = 0;
}
function errorHandler(event){
_("status").innerHTML = "Upload Failed";
}
function abortHandler(event){
_("status").innerHTML = "Upload Aborted";
}
Run Code Online (Sandbox Code Playgroud)
PHP部分
<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
echo "ERROR: Please browse for a file before clicking the upload button.";
exit();
}
if(move_uploaded_file($fileTmpLoc, "test_uploads/$fileName")){ // assuming the directory name 'test_uploads'
echo "$fileName upload is complete";
} else {
echo "move_uploaded_file function failed";
}
?>
Run Code Online (Sandbox Code Playgroud)
Viv*_*mbi 17
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){ }
});
Run Code Online (Sandbox Code Playgroud)
您可以使用表单数据发布所有值,包括图像.
小智 14
要使用Jquery异步上载文件,请使用以下步骤:
步骤1在你的项目中打开Nuget manager并添加包(jquery fileupload(只需要在搜索框中编写它就会出现并安装它.)URL:https://github.com/blueimp/jQuery-File-上传
步骤2在HTML文件中添加以下脚本,这些脚本已通过运行上面的包添加到项目中:
jquery.ui.widget.js
jquery.iframe-transport.js
jquery.fileupload.js
步骤3 按以下代码编写文件上传控件:
<input id="upload" name="upload" type="file" />
Run Code Online (Sandbox Code Playgroud)
第4步 将js方法写为uploadFile,如下所示:
function uploadFile(element) {
$(element).fileupload({
dataType: 'json',
url: '../DocumentUpload/upload',
autoUpload: true,
add: function (e, data) {
// write code for implementing, while selecting a file.
// data represents the file data.
//below code triggers the action in mvc controller
data.formData =
{
files: data.files[0]
};
data.submit();
},
done: function (e, data) {
// after file uploaded
},
progress: function (e, data) {
// progress
},
fail: function (e, data) {
//fail operation
},
stop: function () {
code for cancel operation
}
});
};
Run Code Online (Sandbox Code Playgroud)
步骤5在ready函数调用元素文件上传中,按以下方式启动进程:
$(document).ready(function()
{
uploadFile($('#upload'));
});
Run Code Online (Sandbox Code Playgroud)
步骤6按以下方式编写MVC控制器和操作:
public class DocumentUploadController : Controller
{
[System.Web.Mvc.HttpPost]
public JsonResult upload(ICollection<HttpPostedFileBase> files)
{
bool result = false;
if (files != null || files.Count > 0)
{
try
{
foreach (HttpPostedFileBase file in files)
{
if (file.ContentLength == 0)
throw new Exception("Zero length file!");
else
//code for saving a file
}
}
catch (Exception)
{
result = false;
}
}
return new JsonResult()
{
Data=result
};
}
}
Run Code Online (Sandbox Code Playgroud)
Ali*_*ter 11
没有Jquery的现代方法是使用从用户选择文件时返回的FileList对象<input type="file">,然后使用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
});
});
Run Code Online (Sandbox Code Playgroud)
Dan*_*syo 10
您可以在此处看到一个解决方案,其中包含一个工作演示,允许您预览表单文件并将其提交给服务器.对于您的情况,您需要使用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>
Run Code Online (Sandbox Code Playgroud)
提交的数据是表格数据.在您的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");
});
});
});
Run Code Online (Sandbox Code Playgroud)
MEA*_*bid 10
示例:如果您使用jQuery,则可以轻松上传文件.这是一个小而强大的jQuery插件,http://jquery.malsup.com/form/.
var $bar = $('.ProgressBar');
$('.Form').ajaxForm({
dataType: 'json',
beforeSend: function(xhr) {
var percentVal = '0%';
$bar.width(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
$bar.width(percentVal)
},
success: function(response) {
// Response
}
});
Run Code Online (Sandbox Code Playgroud)
我希望它会有所帮助
您可以使用
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
Run Code Online (Sandbox Code Playgroud)
使用| HTML5的readAsDataURL()或某些base64编码器将文件转换为base64 . 在这里小提琴
var reader = new FileReader();
reader.onload = function(readerEvt) {
var binaryString = readerEvt.target.result;
document.getElementById("base64textarea").value = btoa(binaryString);
};
reader.readAsBinaryString(file);
Run Code Online (Sandbox Code Playgroud)
然后检索:
window.open("data:application/octet-stream;base64," + base64);
Run Code Online (Sandbox Code Playgroud)
您可以使用XMLHttpRequest(没有flash和iframe依赖)在进行异步上载时传递其他参数和文件名.使用FormData附加附加参数值并发送上载请求.
var formData = new FormData();
formData.append('parameter1', 'value1');
formData.append('parameter2', 'value2');
formData.append('file', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'post back url',
data: formData,
// other attributes of AJAX
});
Run Code Online (Sandbox Code Playgroud)
此外,Syncfusion JavaScript UI文件上载仅使用事件参数为此方案提供解决方案.你可以找到的文档在这里和有关此控件的详细信息在这里输入链接的描述在这里
在此处异步查找处理文件的上载过程: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>
Run Code Online (Sandbox Code Playgroud)
您可以通过 JavaScript使用更新的 Fetch API。像这样:
function uploadButtonCLicked(){
var input = document.querySelector('input[type="file"]')
fetch('/url', {
method: 'POST',
body: input.files[0]
}).then(res => res.json()) // you can do something with response
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
}
Run Code Online (Sandbox Code Playgroud)
优点:所有现代浏览器都原生支持Fetch API ,因此您无需导入任何内容。另外,请注意 fetch() 返回一个Promise,然后使用.then(..code to handle response..)异步处理。
这是我的解决方案。
<form enctype="multipart/form-data">
<div class="form-group">
<label class="control-label col-md-2" for="apta_Description">Description</label>
<div class="col-md-10">
<input class="form-control text-box single-line" id="apta_Description" name="apta_Description" type="text" value="">
</div>
</div>
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
Run Code Online (Sandbox Code Playgroud)
和js
<script>
$(':button').click(function () {
var formData = new FormData($('form')[0]);
$.ajax({
url: '@Url.Action("Save", "Home")',
type: 'POST',
success: completeHandler,
data: formData,
cache: false,
contentType: false,
processData: false
});
});
function completeHandler() {
alert(":)");
}
</script>
Run Code Online (Sandbox Code Playgroud)
控制者
[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
[...]
}
Run Code Online (Sandbox Code Playgroud)
使用HTML5和JavaScript,上传异步非常容易,我创建了上传逻辑以及您的html,由于需要api,因此无法完全正常工作,但是如果您有/upload从网站根目录调用的终结点,请演示其工作原理,该代码应为您工作:
const asyncFileUpload = () => {
const fileInput = document.getElementById("file");
const file = fileInput.files[0];
const uri = "/upload";
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = e => {
const percentage = e.loaded / e.total;
console.log(percentage);
};
xhr.onreadystatechange = e => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("file uploaded");
}
};
xhr.open("POST", uri, true);
xhr.setRequestHeader("X-FileName", file.name);
xhr.send(file);
}Run Code Online (Sandbox Code Playgroud)
<form>
<span>File</span>
<input type="file" id="file" name="file" size="10" />
<input onclick="asyncFileUpload()" id="upload" type="button" value="Upload" />
</form>Run Code Online (Sandbox Code Playgroud)
还提供有关XMLHttpReques的更多信息:
XMLHttpRequest对象
所有现代的浏览器都支持XMLHttpRequest对象。XMLHttpRequest对象可用于与后台的Web服务器交换数据。这意味着可以更新网页的某些部分,而无需重新加载整个页面。
创建一个XMLHttpRequest对象
所有现代浏览器(Chrome,Firefox,IE7 +,Edge,Safari,Opera)都具有内置的XMLHttpRequest对象。
创建XMLHttpRequest对象的语法:
变量=新的XMLHttpRequest();
跨域访问
出于安全原因,现代浏览器不允许跨域访问。
这意味着该网页及其尝试加载的XML文件必须位于同一服务器上。
W3Schools上的示例位于W3Schools域上的所有打开的XML文件。
如果要在自己的一个网页上使用上面的示例,则加载的XML文件必须位于自己的服务器上。
有关更多详细信息,您可以在此处继续阅读...
对于 PHP,查找https://developer.hyvor.com/php/image-upload-ajax-php-mysql
HTML
<html>
<head>
<title>Image Upload with AJAX, PHP and MYSQL</title>
</head>
<body>
<form onsubmit="submitForm(event);">
<input type="file" name="image" id="image-selecter" accept="image/*">
<input type="submit" name="submit" value="Upload Image">
</form>
<div id="uploading-text" style="display:none;">Uploading...</div>
<img id="preview">
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
爪哇脚本
var previewImage = document.getElementById("preview"),
uploadingText = document.getElementById("uploading-text");
function submitForm(event) {
// prevent default form submission
event.preventDefault();
uploadImage();
}
function uploadImage() {
var imageSelecter = document.getElementById("image-selecter"),
file = imageSelecter.files[0];
if (!file)
return alert("Please select a file");
// clear the previous image
previewImage.removeAttribute("src");
// show uploading text
uploadingText.style.display = "block";
// create form data and append the file
var formData = new FormData();
formData.append("image", file);
// do the ajax part
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var json = JSON.parse(this.responseText);
if (!json || json.status !== true)
return uploadError(json.error);
showImage(json.url);
}
}
ajax.open("POST", "upload.php", true);
ajax.send(formData); // send the form data
}
Run Code Online (Sandbox Code Playgroud)
PHP
<?php
$host = 'localhost';
$user = 'user';
$password = 'password';
$database = 'database';
$mysqli = new mysqli($host, $user, $password, $database);
try {
if (empty($_FILES['image'])) {
throw new Exception('Image file is missing');
}
$image = $_FILES['image'];
// check INI error
if ($image['error'] !== 0) {
if ($image['error'] === 1)
throw new Exception('Max upload size exceeded');
throw new Exception('Image uploading error: INI Error');
}
// check if the file exists
if (!file_exists($image['tmp_name']))
throw new Exception('Image file is missing in the server');
$maxFileSize = 2 * 10e6; // in bytes
if ($image['size'] > $maxFileSize)
throw new Exception('Max size limit exceeded');
// check if uploaded file is an image
$imageData = getimagesize($image['tmp_name']);
if (!$imageData)
throw new Exception('Invalid image');
$mimeType = $imageData['mime'];
// validate mime type
$allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];
if (!in_array($mimeType, $allowedMimeTypes))
throw new Exception('Only JPEG, PNG and GIFs are allowed');
// nice! it's a valid image
// get file extension (ex: jpg, png) not (.jpg)
$fileExtention = strtolower(pathinfo($image['name'] ,PATHINFO_EXTENSION));
// create random name for your image
$fileName = round(microtime(true)) . mt_rand() . '.' . $fileExtention; // anyfilename.jpg
// Create the path starting from DOCUMENT ROOT of your website
$path = '/examples/image-upload/images/' . $fileName;
// file path in the computer - where to save it
$destination = $_SERVER['DOCUMENT_ROOT'] . $path;
if (!move_uploaded_file($image['tmp_name'], $destination))
throw new Exception('Error in moving the uploaded file');
// create the url
$protocol = stripos($_SERVER['SERVER_PROTOCOL'],'https') === true ? 'https://' : 'http://';
$domain = $protocol . $_SERVER['SERVER_NAME'];
$url = $domain . $path;
$stmt = $mysqli -> prepare('INSERT INTO image_uploads (url) VALUES (?)');
if (
$stmt &&
$stmt -> bind_param('s', $url) &&
$stmt -> execute()
) {
exit(
json_encode(
array(
'status' => true,
'url' => $url
)
)
);
} else
throw new Exception('Error in saving into the database');
} catch (Exception $e) {
exit(json_encode(
array (
'status' => false,
'error' => $e -> getMessage()
)
));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1294053 次 |
| 最近记录: |