jQuery ajax单个文件上传 [英] jQuery ajax single file upload
问题描述
我知道这个问题已经问了很多,并且我尝试了至少10个不同的代码来运行此问题,但没有成功. 我正在尝试使用jquery.ajax上传单个文件,但是它不起作用. 以下代码始终输出:请选择文件",因为未设置文件名或其他名称
I know this question has been asked a lot, and I tried at least 10 different codes to run this without success. I'm trying to upload a single file with jquery.ajax, but it doesn't work. the code below always outputs : 'please choose a file' because the file's name is not set or something
html:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<div id="result"></div>
jquery:
$(function(){
$(document).ready(function(){
var files;
$('input[type=file]').on('change', prepareUpload);
function prepareUpload(event){
files = event.target.files;
};
$(':button').click(function(){
var formData = new FormData();
$.each(files, function(key, value){
formData.append(key, value);
});
alert(formData);
$.ajax({
url: 'check.php',
type: 'GET',
data: formData,
success: function(data){ $('#result').html(data); },
cache: false,
contentType: false,
processData: false
});
});
});
});
php:
if(isset($_GET['file'])){
$filename = $_FILES['file']['name'];
if(isset($filename) && !empty($filename)){
echo 'sup my man?!';
}else{
echo 'please choose a file';
}
}else{
echo 'not set';
}
我不知道问题出在什么地方,我知道这是在FormData
对象创建中,因为警报很好,行不通.
I don't know what the problem is, I know it's in the FormData
object creation because the alert- good to go, doesn't work.
顺便说一句,对我来说,以jQuery编写是非常重要的.
BTW it is really important for me that it would be written in jQuery.
推荐答案
经过数小时的搜索和寻找答案,最终我做到了!!!! 代码如下:)))))
After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))
HTML:
<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
<label>File to stash:</label>
<input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>
jQuery:
$(function(){
$('#uploadBTN').on('click', function(){
var fd = new FormData($("#fileinfo"));
//fd.append("CustomField", "This is some extra data");
$.ajax({
url: 'upload.php',
type: 'POST',
data: fd,
success:function(data){
$('#output').html(data);
},
cache: false,
contentType: false,
processData: false
});
});
});
在upload.php
文件中,您可以访问通过$_FILES['file']
传递的数据.
In the upload.php
file you can access the data passed with $_FILES['file']
.
感谢大家的帮助:)
我从这里得到了答案(进行了一些更改) MDN
I took the answer from here (with some changes) MDN
这篇关于jQuery ajax单个文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!