Javascript jqueryajax文件上传
我可以使用以下jQuery代码使用ajax请求的POST方法执行文件上传吗Javascript jqueryajax文件上传,javascript,jquery,ajax,post,file-upload,Javascript,Jquery,Ajax,Post,File Upload,我可以使用以下jQuery代码使用ajax请求的POST方法执行文件上传吗 $.ajax({ type: "POST", timeout: 50000, url: url, data: dataString, success: function (data) { alert('success'); return false; } }); 如果可能,我是否需要填写数据部分?这是正确的方法吗?我只将文件发布到服务器端
$.ajax({
type: "POST",
timeout: 50000,
url: url,
data: dataString,
success: function (data) {
alert('success');
return false;
}
});
如果可能,我是否需要填写数据
部分?这是正确的方法吗?我只将文件发布到服务器端
我一直在谷歌搜索,但我发现的是一个插件,而在我的计划中,我不想使用它。至少目前是这样。无法通过AJAX上传文件。您可以使用
IFrame
上传文件,而无需刷新页面您可以查看更多详细信息
更新 XHR2支持通过AJAX上传文件。例如,通过对象,但不幸的是,所有/旧浏览器都不支持它
FormData
支持从以下桌面浏览器版本开始
- IE 10+
- 火狐4.0+
- 铬7+
- 狩猎5+
- 歌剧12+
您可以使用
IFrame
上传文件,而无需刷新页面您可以查看更多详细信息
更新 XHR2支持通过AJAX上传文件。例如,通过对象,但不幸的是,所有/旧浏览器都不支持它
FormData
支持从以下桌面浏览器版本开始
- IE 10+
- 火狐4.0+
- 铬7+
- 狩猎5+
- 歌剧12+
- 使用隐藏的iframe并将表单的目标设置为该iframe的名称。这样,在提交表单时,只刷新iframe
- 为iframe的load事件注册事件处理程序以解析响应
- 使用隐藏的iframe并将表单的目标设置为该iframe的名称。这样,在提交表单时,只刷新iframe
- 为iframe的load事件注册事件处理程序以解析响应
XMLHttpRequest()
确实可以进行AJAX上传。不需要iFrame。可以显示上载进度
有关详细信息,请参阅:问题的答案。确实可以使用
XMLHttpRequest()
上传AJAX。不需要iFrame。可以显示上载进度
有关详细信息,请参阅:问题的答案。通过ajax上传文件不再需要iFrame。我最近自己做的。查看以下页面: 更新了答案并将其清理干净。使用getSize函数检查大小,或使用getType函数检查类型。 添加了progressbar html和css代码
var Upload = function (file) {
this.file = file;
};
Upload.prototype.getType = function() {
return this.file.type;
};
Upload.prototype.getSize = function() {
return this.file.size;
};
Upload.prototype.getName = function() {
return this.file.name;
};
Upload.prototype.doUpload = function () {
var that = this;
var formData = new FormData();
// add assoc key values, this will be posts values
formData.append("file", this.file, this.getName());
formData.append("upload_file", true);
$.ajax({
type: "POST",
url: "script",
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
success: function (data) {
// your callback here
},
error: function (error) {
// handle error
},
async: true,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
};
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
var progress_bar_id = "#progress-wrp";
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// update progressbars classes so it fits your code
$(progress_bar_id + " .progress-bar").css("width", +percent + "%");
$(progress_bar_id + " .status").text(percent + "%");
};
如何使用Upload类
//Change id to your id
$("#ingredient_file").on("change", function (e) {
var file = $(this)[0].files[0];
var upload = new Upload(file);
// maby check size or type here with upload.getSize() and upload.getType()
// execute upload
upload.doUpload();
});
Progressbar html代码
<div id="progress-wrp">
<div class="progress-bar"></div>
<div class="status">0%</div>
</div>
通过ajax上传文件不再需要Iframes。我最近自己做的。查看以下页面: 更新了答案并将其清理干净。使用getSize函数检查大小,或使用getType函数检查类型。 添加了progressbar html和css代码
var Upload = function (file) {
this.file = file;
};
Upload.prototype.getType = function() {
return this.file.type;
};
Upload.prototype.getSize = function() {
return this.file.size;
};
Upload.prototype.getName = function() {
return this.file.name;
};
Upload.prototype.doUpload = function () {
var that = this;
var formData = new FormData();
// add assoc key values, this will be posts values
formData.append("file", this.file, this.getName());
formData.append("upload_file", true);
$.ajax({
type: "POST",
url: "script",
xhr: function () {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
myXhr.upload.addEventListener('progress', that.progressHandling, false);
}
return myXhr;
},
success: function (data) {
// your callback here
},
error: function (error) {
// handle error
},
async: true,
data: formData,
cache: false,
contentType: false,
processData: false,
timeout: 60000
});
};
Upload.prototype.progressHandling = function (event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
var progress_bar_id = "#progress-wrp";
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
// update progressbars classes so it fits your code
$(progress_bar_id + " .progress-bar").css("width", +percent + "%");
$(progress_bar_id + " .status").text(percent + "%");
};
如何使用Upload类
//Change id to your id
$("#ingredient_file").on("change", function (e) {
var file = $(this)[0].files[0];
var upload = new Upload(file);
// maby check size or type here with upload.getSize() and upload.getType()
// execute upload
upload.doUpload();
});
Progressbar html代码
<div id="progress-wrp">
<div class="progress-bar"></div>
<div class="status">0%</div>
</div>
如果您想这样做:
$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
if( progressEvent.lengthComputable) {
var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
if( upload) {
console.log( percent + ' uploaded');
} else {
console.log( percent + ' downloaded');
}
}
})
.done( function() {
console.log( 'Finished upload');
});
可能是您的解决方案。如果您想这样做:
$.upload( form.action, new FormData( myForm))
.progress( function( progressEvent, upload) {
if( progressEvent.lengthComputable) {
var percent = Math.round( progressEvent.loaded * 100 / progressEvent.total) + '%';
if( upload) {
console.log( percent + ' uploaded');
} else {
console.log( percent + ' downloaded');
}
}
})
.done( function() {
console.log( 'Finished upload');
});
$("#submit_car").click(function() {
var formData = new FormData($('#car_cost_form')[0]);
$.ajax({
url: 'car_costs.php',
data: formData,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data) {
// ...
},
});
});
这可能是你的解决办法
$("#submit_car").click(function() {
var formData = new FormData($('#car_cost_form')[0]);
$.ajax({
url: 'car_costs.php',
data: formData,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data) {
// ...
},
});
});
编辑:注意ContentType和流程数据
您可以简单地使用它通过Ajax上传文件。。。。。。提交输入不能在表单元素之外:)
编辑:注意ContentType和流程数据
您可以简单地使用它通过Ajax上传文件。。。。。。提交输入不能在表单元素之外:)我想到了一个主意:
Have an iframe on page and have a referencer.
创建一个表单,将输入类型文件元素移动到其中
Form: A processing page AND a target of the FRAME.
结果将发布到iframe,然后您可以将获取的数据发送到所需的图像标记,如下所示:
data:image/png;base64,asdfasdfasdfasdfa
.aftersubmit(function(){
stopPropagation(); // or some other code which would prevent a refresh.
});
页面将被加载
我相信这对我很有效,根据你的情况,你可能会做一些类似的事情:
data:image/png;base64,asdfasdfasdfasdfa
.aftersubmit(function(){
stopPropagation(); // or some other code which would prevent a refresh.
});
我想到了一个主意:
Have an iframe on page and have a referencer.
创建一个表单,将输入类型文件元素移动到其中
Form: A processing page AND a target of the FRAME.
结果将发布到iframe,然后您可以将获取的数据发送到所需的图像标记,如下所示:
data:image/png;base64,asdfasdfasdfasdfa
.aftersubmit(function(){
stopPropagation(); // or some other code which would prevent a refresh.
});
页面将被加载
我相信这对我很有效,根据你的情况,你可能会做一些类似的事情:
data:image/png;base64,asdfasdfasdfasdfa
.aftersubmit(function(){
stopPropagation(); // or some other code which would prevent a refresh.
});
您可以使用方法ajaxSubmit,如下所示:) 选择需要上载到服务器的文件时,表单必须提交到服务器:)
您可以使用方法ajaxSubmit,如下所示:) 选择需要上载到服务器的文件时,表单必须提交到服务器:)
我已经很晚了,但是我正在寻找一个基于ajax的图像上传解决方案,我想要的答案在这篇文章中有点分散。我确定的解决方案涉及FormData对象。我组装了一个基本形式的代码。您可以看到,它演示了如何使用fd.append()将自定义字段添加到表单中,以及在ajax请求完成时如何处理响应数据 上载html:
<!DOCTYPE html>
<html>
<head>
<title>Image Upload Form</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "upload.php",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
</script>
</head>
<body>
<form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
<label>Select a file:</label><br>
<input type="file" name="file" required />
<input type="submit" value="Upload" />
</form>
<div id="output"></div>
</body>
</html>
图片上传表格
函数submitForm(){
控制台日志(“提交事件”);
var fd=新表单数据(document.getElementById(“fileinfo”);
附加(“标签”、“网络上传”);
$.ajax({
url:“upload.php”,
类型:“POST”,
数据:fd,
processData:false,//告诉jQuery不要处理数据
contentType:false//告诉jQuery不要设置contentType
}).完成(功能(数据){
log(“PHP输出:”);
控制台日志(数据);
});
返回false;
}
选择一个文件:
如果您使用php,这里有一种处理上传的方法,包括使用上面html中演示的两个自定义字段
Upload.php
<?php
if ($_POST["label"]) {
$label = $_POST["label"];
}
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 200000)
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
} else {
$filename = $label.$_FILES["file"]["name"];
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("uploads/" . $filename)) {
echo $filename . " already exists. ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"],
"uploads/" . $filename);
echo "Stored in: " . "uploads/" . $filename;
}
}
} else {
echo "Invalid file";
}
?>
我已经晚了,但我正在寻找一种基于ajax的图像上传解决方案
var dataform = new FormData($("#myform")[0]);
//console.log(dataform);
$.ajax({
url: 'url',
type: 'POST',
data: dataform,
async: false,
success: function(res) {
response data;
},
cache: false,
contentType: false,
processData: false
});
$('#UploadB1').click(function(e){
e.preventDefault();
if (!fileupload.valid()) {
return false;
}
var myformData = new FormData();
myformData.append('file', $('#uploadFile')[0].files[0]);
$("#UpdateMessage5").html("Uploading file ....");
$("#UpdateMessage5").css("background","url(../include/images/loaderIcon.gif) no-repeat right");
myformData.append('mode', 'fileUpload');
myformData.append('myid', $('#myid').val());
myformData.append('type', $('#fileType').val());
//formData.append('myfile', file, file.name);
$.ajax({
url: 'include/fetch.php',
method: 'post',
processData: false,
contentType: false,
cache: false,
data: myformData,
enctype: 'multipart/form-data',
success: function(response){
$("#UpdateMessage5").html(response); //.delay(2000).hide(1);
$("#UpdateMessage5").css("background","");
console.log("file successfully submitted");
},error: function(){
console.log("not okay");
}
});
});
<input type="file" id="file">
<button id='process-file-button'>Process</button>
$('#process-file-button').on('click', function (e) {
let files = new FormData(), // you can consider this as 'data bag'
url = 'yourUrl';
files.append('fileName', $('#file')[0].files[0]); // append selected file to the bag named 'file'
$.ajax({
type: 'post',
url: url,
processData: false,
contentType: false,
data: files,
success: function (response) {
console.log(response);
},
error: function (err) {
console.log(err);
}
});
});
if (isset($_FILES) && !empty($_FILES)) {
$file = $_FILES['fileName'];
$name = $file['name'];
$path = $file['tmp_name'];
// process your file
}
<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>
$(document).on('submit', '.fr', function(){
$.ajax({
type: 'post',
url: url, <--- you insert proper URL path to call your views.py function here.
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this) ,
success: function(data) {
console.log(data);
}
});
return false;
});
form = ThisForm(request.POST, request.FILES)
if form.is_valid():
text = form.cleaned_data.get("text")
example_image = request.FILES['example_image']
var jform = new FormData();
jform.append('user',$('#user').val());
jform.append('image',$('#image').get(0).files[0]); // Here's the important bit
$.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: jform,
dataType: 'json',
mimeType: 'multipart/form-data', // this too
contentType: false,
cache: false,
processData: false,
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});