form表单ajax上传图片方法

先引用jquery.form.js

前台代码

<pre>

<form id="form1">

<input id="file_temporaryImage" type="file" name="file_temporaryImage" onchange="TemporaryMedia();"/>

<input type="hidden" id="userpicpath">

<img id="userpic" src=""/>

</form>

<script>

function TemporaryMedia() {

//var image0 = $("input[name='file_temporaryImage']").val();

//判断上传控件中是否选择了图片

var image = $("#file_temporaryImage").val();

if ($.trim(image) == "") {

alert("请选择图片!");

return;

}

//提交请求处理的url

var actionUrl = "/home/kelatoupiao/sctpic/";

//开始ajax操作

$("#form1").ajaxSubmit({

type: "POST",

dataType: "json",

url: actionUrl,

data: {},

success: function (data) {

if (data.success == 1) {

$('#userpicpath').val(data.data);

$('#userpic').attr('src',data.data);

} else {

alert(data.msg);

}

}

});

}

</script>

</pre>

PHP后台代码

<pre>

//上传图片

public function sctpic()

{

$openid = $this->_check_login();

$spath = __DIR__ . '/../../../Public/kelatoupiao/uploads/' . $openid . '_' . time() . '.jpg';

$webpath='/kelatoupiao/uploads/' . $openid . '_' . time() . '.jpg';

if (move_uploaded_file($_FILES["file_temporaryImage"]["tmp_name"], $spath)) {

echo json_encode(array('success' => 1, 'msg'=>'上传成功','data'=>$webpath));

exit();

} else {

echo json_encode(array('success' => 0, 'msg'=>'网络繁忙','data'=>''));

exit();

}

}

</pre>