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));
}
$(文档).ready(函数(){
$(“#上载按钮”)。单击(函数(){
var filename=$(“#文件”).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文件上传方法。您可以在页面上创建一个iframe(使用CSS隐藏),然后将表单定位到该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,只需给它一个
- 它不需要您的服务器以任何特定的方式响应
- 无论使用多少文件,也不管它们在页面上的位置
--尽可能少地使用--
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));
}
使用,您可以使用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()
submit:
$(':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
jQuery('document').ready(函数(){
var input=document.getElementById(“文件”);
var formdata=false;
if(window.FormData){
formdata=新的formdata();
}
input.addEventListener(“更改”,函数(evt){
var i=0,len=this.files.length,img,reader,file;
对于(;i ');
jQuery.ajax({
url:“upload.php”,
类型:“POST”,
数据
<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>
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
$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";
}
?>
<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>
$(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");
});
});
});
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
}
});
$('#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));
}
// 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
});
});
<form method="post" asp-action="Add" enctype="multipart/form-data">
<input type="file" multiple name="mediaUpload" />
<button type="submit">Submit</button>
</form>
[HttpPost]
public async Task<IActionResult> Add(IFormFile[] mediaUpload)
{
//looping through all the files
foreach (IFormFile file in mediaUpload)
{
//saving the files
string path = Path.Combine(hostingEnvironment.WebRootPath, "some-folder-path");
using (var stream = new FileStream(path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
}
private IHostingEnvironment hostingEnvironment;
public MediaController(IHostingEnvironment environment)
{
hostingEnvironment = environment;
}
<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>
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
}
<?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()
)
));
}
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
});