【发布时间】:2015-12-09 21:49:36
【问题描述】:
我正在尝试使用 ajax 上传文件和变量值,但它没有发送。 目前,我正在使用表单并提交,但我需要传递这个变量 body - 以获取 body 的宽度。如何使用 Ajax 做到这一点?
我的代码是:
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
var file = new FormData($('form')[0]);
var body = $('body').width();
e.preventDefault();
$.ajax({
url: "image/upload",
type: "POST",
data: {body:body, file:file},
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
}));
});
<form id="form">
<label>Upload Image File:</label><br/>
<input name="image" type="file" />
<input type="submit" value="Submit" />
</form>
我的控制器是:
public function action_create()
{
$error = 'false';
$bg_path = '';
if(!empty($_FILES["file"]))
{
if ((($_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"))
&& in_array($extension, $allowedExts)) {
if ($_FILES["file"]["error"] > 0)
{
$error = "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
$date = date('YMd');
$path = DOCROOT.'assets/uploads/'.$date.'/';
if (!file_exists($path)) {
mkdir($path, 0775);
}
//other code
}
}
}
【问题讨论】:
-
查看jQuery Ajax File Upload 以及其他链接自其评论部分的帖子。