Javascript 如何使用jQuery异步上传文件?
我想用jQuery异步上传一个文件Javascript 如何使用jQuery异步上传文件?,javascript,jquery,ajax,asynchronous,xmlhttprequest,Javascript,Jquery,Ajax,Asynchronous,Xmlhttprequest,我想用jQuery异步上传一个文件 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 resp
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));
}
$document.readyfunction{
$uploadbutton.clickfunction{
var filename=$file.val;
$.ajax{
类型:POST,,
url:addFile.do,
enctype:“多部分/表单数据”,
数据:{
文件名:filename
},
成功:功能{
上传的警报数据:;
}
};
};
};
文件
注意:这个答案已经过时,现在可以使用XHR上传文件
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));
}
不能使用Ajax上载文件。可以使用iframe或Flash模拟效果。最好的方法是通过iframe发布文件以获得效果。2019更新:这仍然取决于您使用的浏览器。
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));
}
对于新的HTML5文件API,需要了解的一件重要事情是它。如果你瞄准的特定市场对旧版Windows的倾向高于平均水平,你可能无法访问它
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));
}
截至2017年,约5%的浏览器是IE 6、7、8或9中的一种。如果你进入一家大公司,例如,这是一个B2B工具,或者你为培训提供的东西,这个数字可能会飙升。2016年,我与一家在其60%以上的机器上使用IE8的公司打过交道
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));
}
截至本次编辑,时间是2019年,距离我最初的回答已经过去了将近11年。IE9和更低版本在全球范围内约为1%,但仍有较高使用率的集群
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));
}
不管是什么功能,重要的是检查用户使用的浏览器。如果你不这样做,你会很快学到一个痛苦的教训,那就是为什么“为我工作”在交付给客户时不够好。是一个有用的工具,但请注意他们的人口统计数据来源。它们可能与您的不一致。这永远比不上企业环境
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));
}
我2008年的回答如下
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));
}
然而,有一些可行的非JS文件上传方法。您可以在使用CSS隐藏的页面上创建一个iframe,然后以表单为目标发布到该iframe。主页不需要移动
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));
}
这是一个真实的帖子,所以它不是完全互动的。如果你需要状态,你需要一些服务器端的东西来处理。这在很大程度上取决于您的服务器。有更好的机制。PHP plain失败了,但您可以使用或Apache修改来解决这个问题
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));
}
如果需要多个文件上载,最好一次上载一个文件,以克服最大的文件上载限制。将第一个表单发布到iframe,使用上面的命令监视其进度,完成后,将第二个表单发布到iframe,依此类推
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));
}
或者使用Java/Flash解决方案。他们可以更灵活地处理他们的帖子…我发现的一个解决方案是将目标设置为一个隐藏的iFrame。然后,iFrame可以运行JS向用户显示页面加载已完成。为此,我建议使用该插件。您的JavaScript代码应该是:
$(document).ready(function() {
$("#uploadbutton").jsupload({
action: "addFile.do",
onComplete: function(response){
alert( "server response: " + response);
}
});
});
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));
}
。如果您使用轻量级jQuery表单插件,那么只需要大约五行JavaScript
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));
}
挑战在于让AJAX上传作为标准的远程表单工作,因为不理解多部分表单提交。它不会用AJAX请求发送Rails查找的文件数据
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));
}
这就是jQuery表单插件发挥作用的地方
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));
}
以下是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 %>
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));
}
这是Rails控制器的动作,非常普通:
@image = Image.new(params[:image_form])
@image.save
render :text => @image.public_filename
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));
}
在过去的几周里,我一直在Bloggity上使用它,它的效果非常好。这会将文件上传到某处,并通过
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));
}
对回调的响应,没有其他
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));
}
它不依赖于特定的HTML,只需给它一个
它不需要您的服务器以任何特定的方式响应
无论使用多少文件,也不管它们在页面上的位置
-尽可能少地使用-
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
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));
}
-甚至-
$('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');
}
});
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));
}
使用,您可以使用Ajax和jQuery上传文件。不仅如此,你还可以验证文件名、大小和MIME类型,或者用HTML5进度标签或div处理进度事件。最近我不得不制作一个文件上传程序,但我不想使用nor iFrame或插件,经过一些研究,我想出了解决方案
<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>
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));
}
HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
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));
}
现在,单击按钮即可提交$.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;
}
});
});
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));
}
如你所见,使用HTML5和一些研究文件上传不仅成为可能,而且非常简单。尝试一下,因为示例中的一些HTML5组件并不是在每个浏览器中都可用。我一直在使用下面的脚本上传图像,但效果很好
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));
}
HTML
JavaScript
解释
我使用response div显示上传动画和上传完成后的响应
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));
}
最好的一点是,当您使用此脚本时,您可以在文件中发送额外的数据,例如id等。我在脚本中提到了额外的数据
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));
}
在PHP级别,这将作为正常的文件上载工作。额外数据可以作为$u POST数据检索
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));
}
给你
你没有使用插件之类的东西。您可以根据需要更改代码。你不是盲目地在这里编码。这是任何jQuery文件上传的核心功能。实际上是Javascript。你可以很容易地用普通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);
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));
}
jQuery是我以前用来上传文件的另一个好插件。JavaScript代码如下所示:代码。但是,新版本在InternetExplorer中不起作用
$('#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) {
// ...
}
});
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));
}
我已经做了很多搜索,我已经找到了另一个解决方案来上传文件,没有任何插件,只有使用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);
}
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
}
});
};
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));
}
简单Ajax上载程序是另一个选项:
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));
}
跨浏览器-适用于IE7+、Firefox、Chrome、Safari和Opera
支持多个并发上传-即使在非HTML5浏览器中
没有闪存或外部CSS-只有一个5Kb的Javascript文件
使用PHP的APC扩展对完全跨浏览器进度条的可选内置支持
灵活且高度可定制-使用任何元素作为上传按钮,定制您自己的进度指示器
不需要表单,只需提供一个元素作为上传按钮
麻省理工学院许可证-免费用于商业项目
用法示例:
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));
}
var uploader=new ss.SimpleUpload{
按钮:$'uploadBtn',//上传按钮
url:“/uploadhandler”,//服务器端上载处理程序的url
名称:'userfile',//上传文件的参数名称
onSubmit:函数{
this.setProgressBar$'progressBar';//指定elem作为我们的进度条
},
onComplete:函数文件,响应{
//上传完成后做任何事情
}
};
你可以用
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
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));
}
要使用Jquery异步上载文件,请使用以下步骤:
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));
}
第1步在您的项目中打开Nuget manager并添加jquery文件上传包—只需将其写入搜索框,它就会出现并安装。
网址:
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));
}
步骤2:在HTML文件中添加以下脚本,这些脚本已通过运行上述程序包添加到项目中:
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));
}
jquery.ui.widget.js
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));
}
jquery.iframe-transport.js
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));
}
jquery.fileupload.js
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));
}
步骤3:按照以下代码编写文件上传控制:
<input id="upload" name="upload" type="file" />
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));
}
就绪功能调用元素文件上传中的步骤5,启动流程如下:
$(document).ready(function()
{
uploadFile($('#upload'));
});
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
};
}
}
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));
}
步骤6编写MVC控制器并按照以下步骤执行操作:
$(document).ready(function()
{
uploadFile($('#upload'));
});
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
};
}
}
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));
}
使用| HTML5的或将文件转换为base64。
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));
}
然后检索:
window.open("data:application/octet-stream;base64," + base64);
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));
}
我在过去做过的最简单、最健壮的方法是,在表单中只针对一个隐藏的iFrame标记,然后它将在iFrame中提交,而无需重新加载页面
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));
}
如果您不想使用插件、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>
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));
}
在服务器端,在传输文件数据之前,创建cookie
setcookie('iDownloader', true, time() + 30, "/");
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));
}
插件将看到cookie,然后触发onComplete回调。您可以使用jQuery.ajax简单地上传
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));
}
HTML:
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));
}
文件:
CSS
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));
}
.progress{显示:无;}
Javascript:
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));
}
$document.readyfunctionev{
$upload表单。在“提交”时,函数EV{
防止违约;
$.ajax{
xhr:函数{
var progress=$'。progress',
xhr=$.ajaxSettings.xhr;
进步.表演;
xhr.upload.onprogress=functionev{
如果ev.Length可计算{
var percentComplete=已加载的总功率/总功率*100;
进度。完成百分比;
如果完成百分比===100{
progress.hide.0;
}
}
};
返回xhr;
},
url:'upload.php',
键入:“POST”,
数据:新FormDatathis,
contentType:false,
cache:false,
processData:false,
成功:functiondata、status、xhr{
// ...
},
错误:函数XHR、状态、错误{
// ...
}
};
};
};
为未来的读者做总结
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));
}
异步文件上载
使用HTML5
如果和都支持HTML5功能,则可以使用$.ajax方法使用jQuery上载文件
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));
}
您也可以发送文件,但无论采用哪种方式,都必须提供文件API来处理文件,以便使用XMLHttpRequest Ajax发送文件
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));
}
有关快速、纯JavaScript无jQuery示例,请参见
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));
}
退路
当HTML5不受支持时,没有文件API唯一的纯JavaScript解决方案没有Flash或任何其他浏览器插件是隐藏的iframe技术,它允许在不使用XMLHttpRequest对象的情况下模拟异步请求
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));
}
它包括将iframe设置为带有文件输入的表单的目标。当用户提交请求时,会发出请求并上载文件,但响应为disp
在iframe中进行分层,而不是重新呈现主页面。隐藏iframe可以使整个过程对用户透明,并模拟异步请求
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));
}
如果操作得当,它几乎可以在任何浏览器上工作,但是它有一些警告,比如如何从iframe获得响应
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));
}
在这种情况下,您可能更喜欢使用像这样的包装器插件,它使用iframe技术,但也提供了一种允许仅使用$.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!");
});
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));
}
插件
只是一个小包装器,它为jQuery的ajax方法添加了回退支持,但是前面提到的许多插件喜欢或包括从HTML5到不同回退的整个堆栈以及一些有用的特性,以简化过程。根据您的需求和需求,您可能需要考虑一个裸露的实现或这两个插件中的任何一个。< P>查找文件的上传过程,这里异步地:
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));
}
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));
}
链接中的示例
<?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>
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));
}
您可以使用表单数据发布所有值,包括图像。这是我的解决方案
<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>
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));
}
这里只是另一个解决方案,如何上传文件没有任何插件
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));
}
使用简单的Java脚本和带有进度条的AJAX
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));
}
HTML部分
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));
}
PHP部分
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));
}
您可以看到一个已解决的解决方案,其中包含一个工作演示,允许您预览表单文件并将其提交到服务器。对于您的情况,您需要使用以方便将文件上载到服务器:
<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>
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));
}
示例:如果您使用jQuery,您可以轻松地上传文件。这是一个小而强大的jQuery插件
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));
}
实例
我希望这会有帮助这是一个老问题,但仍然没有正确答案,因此:
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));
}
你试过了吗
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));
}
下面是上面链接中的一个可能解决您的问题的示例:
$('#fileupload').fileupload({
add: function (e, data) {
var that = this;
$.getJSON('/example/url', function (result) {
data.formData = result; // e.g. {id: 123}
$.blueimp.fileupload.prototype
.options.add.call(that, e, data);
});
}
});
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));
}
使用HTML5和JavaScript,异步上传非常简单,我将与html一起创建上传逻辑,这并不完全有效,因为它需要api,但演示它是如何工作的,如果您的网站根目录中有名为/upload的端点,则此代码应适用于您:
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));
}
常量asyncFileUpload==>{
const fileInput=document.getElementByIdfile;
const file=fileInput.files[0];
consturi=/upload;
const xhr=新的XMLHttpRequest;
xhr.upload.onprogress=e=>{
常数百分比=e.加载/e.总计;
控制台。对数百分比;
};
xhr.onreadystatechange=e=>{
如果xhr.readyState==4&&xhr.status==200{
console.log文件上传;
}
};
openPOST,uri,true;
xhr.setRequestHeaderX-FileName,file.name;
xhr.sendfile;
}
文件
您可以通过JavaScript使用更新的。像这样:
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));
}
优点:所有现代浏览器都支持FetchAPI,因此您无需导入任何内容。另外,请注意fetch返回一个,然后使用.then..code来处理响应。。异步的 没有Jquery的现代方法是,当用户选择一个文件时,使用您从中获取的对象,然后使用该对象发布包裹在对象周围的文件列表
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));
}
您可以使用JavaScript或jQuery进行异步多文件上传,而无需使用任何插件。您还可以在进度控件中显示文件上载的实时进度。我遇到了2个不错的链接-
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));
}
服务器端语言是C,但您可以对其进行一些修改,使其与其他语言(如PHP)一起工作
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));
}
文件上载ASP.NET核心MVC:
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));
}
在视图中,以html格式创建文件上载控件:
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));
}
<form method="post" asp-action="Add" enctype="multipart/form-data">
<input type="file" multiple name="mediaUpload" />
<button type="submit">Submit</button>
</form>
对于PHP,请查找
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));
}
HTML
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));
}
PHP
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));
}
在使用XMLHttpRequest进行异步上载时,您可以在不依赖flash和iframe的情况下传递附加参数和文件名。使用FormData追加附加参数值并发送上载请求
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));
}
此外,Syncfusion JavaScript UI文件上载仅使用事件参数就为该场景提供了解决方案。您可以在此处找到有关此控件的文档和更多详细信息输入链接说明是的,您可以发布到iframe并在那里捕获文件。不过,我在这方面的经验非常有限,因此我无法对此发表评论。小结:在最新版本的chrome和firefox中,这是可能的,IE9和LESS中不支持。根据记录,如果浏览器支持文件API,现在可以进行纯AJAX文件上传-这是一个非常古老的答案,但有点误导。。IE早在IE7就支持XHR,早在IE5就通过ActiveX支持XHR。实现这一点的实际方法当然是针对flash shockwave组件,或者推出flash/ActiveX Silverlight控件。如果您可以发起请求并通过javascript处理响应,那就是ajax。。尽管如此,ajax是xhr的同义词,但它本身并没有描述传递/交换有效负载的下划线机制/组件。@BrettCaswell我并不是说ajax/xhr不可能,只是说不可能在旧版上发布文件?
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));
}
e上传jQuery。做这种上传黑客不是一种愉快的体验,所以人们喜欢使用现成的解决方案。这里有几个:---您可以使用jquery插件作为关键字或在Github上搜索NPM上的更多项目。您只能获得文件名,因为您的var文件名获得了$'file'的值,不是inputHere中的文件,这是一个很好的文件:-HTML5 ajax上传-对于不受支持的浏览器,优雅地回退到iFrame-多文件异步上传我们使用过它,它工作得很好。还请勾选此项:,此处说明如何通过jQuery@Jimmy他将如何获取位于输入中的文件呢?显然IEPerfectless不支持!这应该更高