我正在尝试通过FormData和XMLHttpRequest上传文件,文件无法保存到文件夹中我不知道哪里错了。 最后,我希望可以发送此消息,因为我得到这个:你的帖子没有太多的上下文来解释代码部分;请更清楚地解释您的情景。
upload.php的
<?
$target_path = "uploads/";
$target_path = $target_path . basename( $_FILES['filetext']['name']);
$exten = basename( $_FILES['filetext']['name']);
$exten = substr($exten, -4);
if($exten == ".png" || $exten == ".jpg" || $exten == ".bmp" || $exten == ".gif")
{
if(move_uploaded_file($_FILES['filetext']['tmp_name'], $target_path))
{
echo $_FILES['filetext']['name']."\n". $test;
}
else
{
echo 0;
}
}
else
{
echo 0;
}?>
upload.js
$(document).ready(function(){
function defaults(e){
e.stopPropagation();
e.preventDefault();
}
$(":file").live("change", function(){
handleFiles(this.files);
});
function handleFiles(files,e){
// Traverse throught all files and check if uploaded file type is image
var imageType = /image.*/;
var file = files[0];
// check file type
if (!file.type.match(imageType)) {
alert("File \""+file.name+"\" is not a valid image file, Are you trying to screw me :( :( ");
return false;
}
// check file size
if (parseInt(file.size / 1024) > 2050) {
alert("File \""+file.name+"\" is too big. I am using shared server :P");
return false;
}
var info = '<div class="preview active-win"><div class="preview-image"><img ></div><div class="progress-holder"><span id="progress"></span></div><span class="percents"></span><div style="float:left;">Uploaded <span class="up-done"></span> KB of '+parseInt(file.size / 1024)+' KB</div>';
$(".upload-progress").show("fast",function(){
$(".upload-progress").html(info);
uploadFile(file);
});
}
function uploadFile(file){
var fd = new FormData();
fd.append('filez', file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "upload.php", true);
xhr.send(fd);
function uploadProgress(event) {
if (event.lengthComputable) {
$("#progress").css("width",(event.loaded / event.total) * 100 + "%");
$(".percents").html(" "+((event.loaded / event.total) * 100).toFixed() + "%");
$(".up-done").html((parseInt(event.loaded / 1024)).toFixed(0));
} else {
alert("Failed to compute file upload length");
}
}
function uploadComplete(event) {
$("#progress").css("width","100%");
$(".percents").html("100%");
$(".up-done").html((parseInt(file.size / 1024)).toFixed(0));
}
function uploadFailed(event) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(event) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
}
});
HTML
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="filez" accept="image/*">
<div class="upload-progress"></div>
</form>
答案 0 :(得分:0)
你的代码有点乱。
由于您使用的是jQuery,请查看本文末尾:https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/FormData/Using_FormData_Objects
干杯。