1. 程式人生 > >TP5中含圖片的表單ajax上傳(不含圖片回顯)

TP5中含圖片的表單ajax上傳(不含圖片回顯)

前端:

<div class="page-container">
	<form action="" method="post" class="form form-horizontal" id="formadd">
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2">
				<span class="c-red">*</span>
				標題:</label>
			<div class="formControls col-xs-6 col-sm-6">
				<input type="text" class="input-text" value="" placeholder="" id="title" name="title">
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2">
				<span class="c-red">*</span>
				導圖:</label>
			<div class="formControls col-xs-6 col-sm-6">
				<input type="file" class="input-text" value="" placeholder="" id="image" name="image" >
			</div>
		</div>
		<div class="row cl">
			<label class="form-label col-xs-4 col-sm-2">
				<span class="c-red">*</span>
				正文:</label>
			<div class="formControls col-xs-6 col-sm-6">
				<textarea name="content" id="detailinfo" style="width: 700px;height: 900px;" cols="" rows=""></textarea>
			</div>
		</div>
		<div class="row cl">
			<div class="col-9 col-offset-2">
				<input class="btn btn-primary radius" type="submit" value="  提交  ">
			</div>
		</div>
	</form>
</div>

ajax提交:

$('#formadd').submit(function(event){
		//ajax方式提交form表單資訊給伺服器
	event.preventDefault(); //阻止瀏覽器form表單提交
	var form=document.getElementById("formadd");
    var fd =new FormData(form);
	$.ajax({
		url:'url地址/upload',
		type:'post',
		data:fd,
		processData: false,  // 告訴jQuery不要去處理髮送的資料
                contentType: false,   // 告訴jQuery不要去設定Content-Type請求頭
                dataType:'json',		
		success:function(msg){
			if(msg.code === 1){
          		layer.alert('新增成功',{icon: 6}, function(){
          			parent.window.location.href = parent.window.location.href; 
				});
   			}else{
          		layer.alert('新增失敗', {icon: 5});  
		  }
		}
	});
});

後端:

public function upload(){
        //圖片
        $file = Request::instance()->file("image");
        // 移動到框架應用根目錄/public/uploads/form/ 目錄下
        if($file){
            $info = $file->validate(['size'=>600678,'ext'=>'jpg,png,jpeg'])->move(ROOT_PATH .DS.'public'.DS.'uploads'.DS.'form');
            if($info){
                // 成功上傳後 獲取上傳目錄
                $img = $info->getSaveName();
                $imgpath = DS.'uploads'.DS.'form'.DS.$img;
                $data=$_POST;
                $data['image']=str_replace(DS,"/",$imgpath);
                $result = Db::table('表名')->insert($data);
                if($result){
                     $res = array(
                        'code' => 1,
                        'msg'  => '新增成功'
                    );
                }else{
                    $res = array(
                        'code' => 2,
                        'msg'  => '新增失敗'
                    );
                }
            }
         }else{
            $res = array(
                'code' => 3,
                'msg'  => '圖片上傳失敗'
            );
         }
        echo json_encode($res);
	}