javascript - 如何使用 jQuery 异步上传文件?
我想使用 jQuery 异步上传一个文件。
$(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: ");
}
});
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<span>File</span>
<input type="file" id="file" name="file" size="10"/>
<input id="uploadbutton" type="button" value="Upload"/>文件没有被上传,我只得到了文件名。我该如何解决这个问题?
答案#1
使用 HTML5,你可以通过 Ajax 和 jQuery 实现文件上传。不仅如此,你还可以进行文件验证(名称、大小和 MIME 类型),或者使用 HTML5 的 progress 标签(或 div)处理进度事件。最近我需要制作一个文件上传器,但我不想使用 Flash、Iframes 或插件,经过一些研究后,我想出了这个解决方案。
HTML:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>
首先,如果你愿意,可以进行一些验证。例如,在文件的 .on('change') 事件中:
$(':file').on('change', function () {
var file = this.files[0];
if (file.size > 1024) {
alert('max upload size is 1k');
}
// Also see .name, .type
});
现在使用按钮点击来提交 $.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;
}
});
});
如你所见,通过 HTML5(以及一些研究),文件上传不仅变得可能,而且非常容易。使用 Google Chrome 尝试一下,因为示例中的一些 HTML5 组件并不是每个浏览器都支持。
答案#2
2019 更新:这仍然取决于你的目标人群使用的浏览器。
理解“新”HTML5 file API 的一个重要点是,直到 IE 10 才支持它。如果你所针对的特定市场使用旧版 Windows 的比例高于平均水平,你可能无法使用它。
截至2017年,约有5%的浏览器是IE 6、7、8或9之一。如果你进入一家大公司(例如,这是一个B2B工具或者你为培训提供的一些内容),这个数字可能会激增。2016年,我处理过一家公司,他们有超过60%的机器使用IE8。
截至本次编辑是2019年,距离我最初的回答已经将近11年。IE9及以下的使用率在全球范围内约为1%,但仍然存在使用率较高的群体。
从这件事中最重要的收获——无论功能如何——是,检查你的用户使用的是哪种浏览器。如果不这样做,你将很快且痛苦地明白为什么“对我有效”在交付给客户时是不够的。caniuse 是一个有用的工具,但要注意他们的人口统计数据来源。它们可能与你的数据不一致。在企业环境中,这一点尤为真实。
我2008年的答案如下。
然而,也有可行的非 JavaScript 文件上传方法。你可以在页面上创建一个 iframe(通过 CSS 将其隐藏),然后将你的表单目标设置为向该 iframe 提交。主页面不需要移动。
这是一个“真实的”帖子,所以它不是完全互动的。如果你需要状态,你需要一些服务器端来处理。这取决于你的服务器情况差别很大。ASP.NET 有更好的机制。纯 PHP 不行,但你可以使用 Perl 或 Apache 修改来解决这个问题。
如果您需要上传多个文件,最好一次上传一个文件(以克服最大文件上传限制)。将第一个表单提交到 iframe,使用上述方法监控其进度,当其完成后,将第二个表单提交到 iframe,依此类推。
或者使用 Java/Flash 解决方案。它们在帖子功能上要灵活得多……
答案#3
我建议为此使用 Fine Uploader 插件。你的 JavaScript 代码将是:
$(document).ready(function() {
$("#uploadbutton").jsupload({
action: "addFile.do",
onComplete: function(response){
alert( "server response: " + response);
}
});
});
答案#4
注意:此答案已过时,现在可以使用 XHR 上传文件。
您不能使用 XMLHttpRequest(Ajax)上传文件。您可以使用 iframe 或 Flash 来模拟效果。优秀的 jQuery 表单插件可以通过 iframe 提交您的文件以实现该效果。
答案#5
为未来的读者做总结。
异步文件上传
使用 HTML5
如果支持 FormData 和 File API(两者都是 HTML5 特性),你可以使用 $.ajax() 方法 使用 jQuery 上传文件。
你也可以在没有 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!");
});
有关快速、纯 JavaScript(无需 jQuery)示例,请参见“使用 FormData 对象发送文件”。
后备
当 HTML5 不被支持(没有 文件 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!");
});
插件
Bifröst 只是一个小包装器,为 jQuery 的 ajax 方法添加了后备支持,但前面提到的许多插件(例如 jQuery Form Plugin 或 jQuery File Upload)都包含从 HTML5 到不同后备的整个堆栈,以及一些简化此过程的有用功能。根据您的需要和要求,您可能需要考虑轻量级实现或任何这些插件。
答案#6
这个 AJAX 文件上传 jQuery 插件会把文件上传到某个地方,并将响应传递给回调函数,仅此而已。
- 这不依赖于特定的 HTML,只需给它一个
<input type="file"> - 它不要求您的服务器以任何特定方式响应
- 无论你使用多少文件,或者它们在页面上的位置,都无关紧要
-- 尽量少用 --
$('#one-specific-file').ajaxfileupload({
'action': '/upload.php'
});
-- 或者和……一样多 --
$('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');
}
});
答案#7
我一直在使用下面的脚本来上传图像,这个脚本碰巧运行得很好。
HTML
<input id="file" type="file" name="file"/>
<div id="response"></div>
JavaScript
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);
});
解释
我使用响应 div 来显示上传动画,并在上传完成后显示响应。
最棒的部分是,当你使用这个脚本时,你可以随文件一起发送额外的数据,例如ID等。我在脚本中把它提到为extra-data。
在 PHP 层面,这将像普通文件上传一样工作。额外的数据可以作为 $_POST 数据获取。
在这里,你没有使用插件之类的东西。你可以随意更改代码。你不是在盲目地编程。这是任何 jQuery 文件上传的核心功能。实际上是 JavaScript。
答案#8
你可以在原生 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);
答案#9
你可以简单地使用 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>
CSS
.progress { display: none; }
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) {
// ...
}
});
}));
});
答案 #10
我过去做这件事情最简单且最稳妥的方法,就是将你的表单直接指向一个隐藏的 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>
您也可以在 onLoad 中读取 iframe 的内容,以检查服务器错误或成功响应,然后将其输出给用户。
Chrome、iFrames 与 onLoad
-注意- 只有当你对在上传/下载时如何设置用户界面阻塞器感兴趣时,才需要继续阅读
目前,当 Chrome 用于传输文件时,它不会触发 iframe 的 onLoad 事件。Firefox、IE 和 Edge 在文件传输时都会触发 onload 事件。
我发现对 Chrome 唯一有效的解决办法是使用 cookie。
基本上,当开始上传/下载时要做的事情是:
- [客户端] 启动一个定时器以查找 cookie 是否存在
- [服务器端] 对文件数据进行所需的任何操作
- [服务器端] 为客户端间隔设置 Cookie
- [客户端] Interval 会检测到 cookie 并像 onLoad 事件一样使用它。例如,你可以启动一个 UI 阻挡器,然后在 onLoad(或 cookie 创建时)移除这个 UI 阻挡器。
使用 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');
});
在服务器端,就在传输文件数据之前,创建这个 cookie
setcookie('iDownloader', true, time() + 30, "/");
该插件将看到 cookie,然后触发 onComplete 回调。
答案#11
我已经在 Rails 环境中写了这个。如果你使用轻量级的 jQuery-form 插件,这只有大约五行 JavaScript。
挑战在于让 AJAX 上传工作,因为标准的 remote_form_for 不理解多部分表单提交。使用 AJAX 请求它不会发送 Rails 所需的文件数据。
这就是 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 %>
这是相关的 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.
},
});
});
这是 Rails 控制器的操作,非常普通:
@image = Image.new(params[:image_form])
@image.save
render :text => @image.public_filename
过去几周我一直和 Bloggity 一起使用这个,它运行得非常好。
答案#12
Simple Ajax 上传器是另一种选择:
https://github.com/LPology/Simple-Ajax-Uploader
- 跨浏览器——兼容 IE7 及以上版本、Firefox、Chrome、Safari、Opera
- 支持多重、同时上传——即使在非HTML5浏览器中
- 没有 Flash 或外部 CSS —— 只有一个 5Kb 的 Javascript 文件
- 可选的内置支持,用于完全跨浏览器的进度条(使用 PHP 的 APC 扩展)
- 灵活且高度可定制——可以将任何元素用作上传按钮,自定义你的进度指示器样式
- 不需要表格,只需提供一个作为上传按钮的元素
- MIT 许可证——可免费用于商业项目
示例用法:
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
}
});
答案 #13
我找到的一个解决方案是让 <form> 以隐藏的 iFrame 为目标。然后 iFrame 可以运行 JS 向用户显示它已经完成(在页面加载时)。
答案#14
这里只是另一种上传文件的方法(无需任何插件)
使用简单的JavaScript和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>
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";
}
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";
}
?>
这是示例应用程序
答案#15
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) {
// ...
}
});
我已经进行了大量搜索,并且找到了另一种无需任何插件,仅使用 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);
}
答案#16
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){ }
});
您可以使用表单数据提交包括图片在内的所有值。
答案#17
一种现代方法 不使用 Jquery 是使用用户选择文件时从 <input type="file"> 获取的 FileList 对象,然后使用 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
});
});
答案#18
使用 Jquery 异步上传文件,请按照以下步骤:
步骤 1 在您的项目中打开 Nuget 管理器并添加包(jquery fileupload(只需在搜索框中输入,它就会出现并安装。))URL: https://github.com/blueimp/jQuery-File-Upload
第2步 在HTML文件中添加以下脚本,这些文件已经通过运行上述包添加到项目中:
jquery.ui.widget.js
jquery.iframe-传输.js
jquery.fileupload.js
步骤 3 根据以下代码编写文件上传控件:
<input id="upload" name="upload" type="file" />
步骤 4 编写一个名为 uploadFile 的 JS 方法,如下所示:
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
}
});
};
步骤 5 在 ready 函数中调用元素文件上传以按照如下方式启动该过程:
$(document).ready(function()
{
uploadFile($('#upload'));
});
第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
};
}
}
答案#19
这是我的解决方案。
<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>
以及 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>
控制器
[HttpPost]
public ActionResult Save(string apta_Description, HttpPostedFileBase file)
{
[...]
}
答案#20
对于你的情况,你需要使用 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>
提交的数据是一个 formdata。在你的 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");
});
});
});
答案#21
你可以使用
$(function() {
$("#file_upload_1").uploadify({
height : 30,
swf : '/uploadify/uploadify.swf',
uploader : '/uploadify/uploadify.php',
width : 120
});
});
演示
答案#22
示例:如果你使用 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
}
});
我希望这会有帮助
答案#23
使用 |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);
然后检索:
window.open("data:application/octet-stream;base64," + base64);
答案#24
在使用 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
});
此外,Syncfusion JavaScript UI 文件上传通过简单地使用事件参数就能为此场景提供解决方案。您可以在此处找到文档,并在此处了解有关此控件的更多详细信息 输入链接描述
