我希望上传一个文件,将其发送到JavaScript formData对象中,然后通过ajax发送到一些php脚本,该脚本将文件放入数据库中。当我在profile.php中上传文件,将其发送到JavaScript formData对象中,并将其发送回到profile.php时,它运行良好。问题是当我想要将formData对象发送到其他不是profile.php的php脚本时,它无法正常工作。
这是我的代码: profile.php
这是我的代码: profile.php
<form role="form" id="editUserProfile" method="post" action="" enctype="multipart/form-data">
<input type="file" id="filename" name="filename" class="file-input" accept="image/*"/></a>
<button type="submit">Save</button
</form>
javascript.js
$('#editUserProfile').validate({
submitHandler: function (form) {
var aFormData = new FormData();
aFormData.append("filename", $('#filename').get(0).files[0]);
$.ajax({
type: "POST",
url: "script.php",
data: aFormData,
success: function(data){
window.location.reload(true);
}
})
}
});
然后我想在另一个php脚本(script.php)中检查文件是否已上传。
if(is_uploaded_file($_FILES['filename']['tmp_name']) && getimagesize($_FILES['filename']['tmp_name']) != false){
$size = getimagesize($_FILES['filename']['tmp_name']);
$type = $size['mime'];
$imgfp = fopen($_FILES['filename']['tmp_name'], 'rb');
$size = $size[3];
$name = $_FILES['filename']['name'];
$maxsize = 99999999;
if($_FILES['userfile']['size'] < $maxsize ){
$dbh = new PDO("mysql:host=localhost;dbname=test", 'root');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO table (image_type ,image, image_size, image_name) VALUES (? ,?, ?, ?)");
$stmt->bindParam(1, $type);
$stmt->bindParam(2, $imgfp, PDO::PARAM_LOB);
$stmt->bindParam(3, $size);
$stmt->bindParam(4, $name);
$stmt->execute();
}else{
throw new Exception("File Size Error");
}
}