1. 程式人生 > >tp3.2 ajax上傳圖片(可以用,樣式要自己寫)

tp3.2 ajax上傳圖片(可以用,樣式要自己寫)

html頁面

<form id="mbInfoForm" action="" method="POST">
<input type="hidden" name="idcard_up" id="idcard_up">
<table class="formTbl">

<tr>
<td class="prop"></td>
<td>
<div class="clearfix">
<div style="float: left;width: 50%;text-align: center">

<p style="padding: 8px 0;">身份證正面</p>
<div style="position: relative;top: 0;width: 204px;height: 150px;text-align: center;border: 2px dashed #B9B9B9;">
<input style="position: absolute;top: 0;left: 0;opacity: 0;z-index: 1;width: 204px;height: 150px;" id="pic_up" type="file" class="input" multiple="true">

<img <if condition="$vo.card_img neq null">src="{$vo.card_img}"<else/>src="/Upload/idcard/z_add.png"</if> id="pic_up_img">
                  //如果有圖片就顯示查出來的圖片,否則顯示一個預設的圖片
</div>
</div>

</div>

</td>
</tr>


<tr>
<td class="prop">&nbsp;</td>
<td>
<a class="bYellow buttonL" href="javascript:;" onclick="editMemberInfo();">儲存並繼續</a>
<a class="bYellow buttonL" href="javascript:;" onclick="goNext(2);">跳過</a>
</td>
</tr>
</table>
</form>

<script>
$('#pic_up').change(function(event) {
var formData = new FormData();
formData.append("file", $(this).get(0).files[0]);
$.ajax({
url:"__URL__/uploadidcard",
dataType:'json',
type:'POST',
data:formData,
cache: false,
contentType: false, //不可缺
processData: false, //不可缺
success:function(data){
console.log(data.path)
if(data.code == 1){
$("#pic_up_img").attr("src",data.path);//將php傳過來的圖片付給圖片src顯示
$("#idcard_up").val(data.path);//將路徑儲存到hidden裡通過form一起儲存
}else{
alert(data.msg);
}
}
});
});
</script>
//php端
public function uploadidcard(){
import('ORG.Net.UploadFile');
$upload = new UploadFile(); // 例項化上傳類
$upload->maxSize = 1*1024*1024; //設定上傳圖片的大小
$upload->allowExts = array('jpg','png','gif','jpeg'); //設定上傳圖片的字尾
$upload->uploadReplace = true; //同名則替換
$upload->savePath='./Upload/idcard/front/';//儲存路徑建議與主檔案平級目錄或者平級目錄的子目錄來儲存
if(!$upload->upload()) {
// 上傳錯誤提示錯誤資訊
$msg = $upload->getErrorMsg();
$data['data'] = '';
$data['code'] = -1;
$data['msg'] = $msg;
exit(json_encode($data));
}else{
// 上傳成功 獲取上傳檔案資訊
$info = $upload->getUploadFileInfo();
import('ORG.ThinkImage.ThinkImage');
$image = new ThinkImage(THINKIMAGE_GD);
    //APP_PATH_NEW 這個是自定義的相當於http://xxx.com
       $imgurl = APP_PATH_NEW.'/Upload/idcard/front/'.$info[0]['savename'];
$image->open($imgurl);
// 按照原圖的比例生成一個最大為150*150的縮圖
$image->thumb(150,150)->save($imgurl);

$data['path'] = 'http://'.$_SERVER['HTTP_HOST'].'/Upload/idcard/front/'.$info[0]['savename'];
$data['code'] = 1;
$data['msg'] = '上傳成功';
exit(json_encode($data));
}
}