gpt4 book ai didi

javascript - 如何使用 jQuery 异步上传文件?

转载 作者:行者123 更新时间:2023-11-28 05:33:19 25 4
gpt4 key购买 nike

我想使用 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"/>

我只获取文件名,而不是上传文件。我该如何解决这个问题?

最佳答案

HTML5您可以使用 Ajax 和 jQuery 进行文件上传。不仅如此,您还可以进行文件验证(名称、大小和 MIME 类型)或使用 HTML5 进度标记(或 div)处理进度事件。最近要做一个文件 uploader ,但是我不想用Flash也没有 iframe 或插件,经过一些研究我想出了解决方案。

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(和一些研究),文件上传不仅变得可能,而且 super 简单。尝试使用 Google Chrome因为示例中的某些 HTML5 组件并非在每个浏览器中都可用。

关于javascript - 如何使用 jQuery 异步上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39536630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com