上传图片功能的实现

html 中

< form method="POST" action="..." enctype="multipart/form-data">
< div class="box" style="padding:20px 25px;">
    // 隐藏域传 tid
    < input type="hidden" name="data[tid]" value="<{$tid}>">
    < p>标题:< /p>
    < input type="text" name="data[title]" class="ma_title" placeholder="请输入标题">
    < p>上传图片:< /p>
    < div class="ma_photo">
        < input id="biaoqian_file" name="img" type="file" style="width:80px;height:80px;position: absolute;top: 10px;opacity: 0;">
        < img src="/tpl/default/static/images/hm.png" alt="" style="height:80px;margin-top: 10px;border-radius: 5px;vertical-align: top;">
        < div class="ma_photo_box">  这个div是用来显示图片的
        < /div>
    < /div>
    < p>记录回忆:< /p>
    < textarea name="data[content]" class="ma_neirong" placeholder="请填写您要记录的故事">< /textarea>
< /div>
< button class="next">下一步< /button>

< /form>

js 中

// 上传图片并展示,可回显可传值给后台

document.getElementById('biaoqian_file').onchange = function() {
      var imgFile = this.files[0];
		 var fr = new FileReader();
   	 fr.onload = function() {
        		// alert(fr.result);
        		$('.ma_photo_box').append('<img src="'+fr.result+'" alt="">');
        		$('.ma_photo_box').width($('.ma_photo_box img').length * 90);
        		// document.getElementById('image').getElementsByTagName('img')[0].src = fr.result;
    };
   	 fr.readAsDataURL(imgFile);
};

控制器中
获取前台传过来的图片并上传到一个位置

  $file = $_FILES['img'];		//得到传输的数据,前台标签名是 img,所以用 img 来接收
	echo '<pre>';
	var_dump($file);
	var_dump($file['tmp_name']);

	//得到文件名称
	$name = $file['name'];
	$type = strtolower(substr($name,strrpos($name,'.')+1)); //得到文件类型,并且都转化成小写
	$allow_type = array('jpg','jpeg','gif','png'); //定义允许上传的类型
	//判断文件类型是否被允许上传
	if(!in_array($type, $allow_type)){
	  //如果不被允许,则直接停止程序运行
	  return ;
	}
	//判断是否是通过HTTP POST上传的
	if(!is_uploaded_file($file['tmp_name'])){
	  //如果不是通过HTTP POST上传的
	  return ;
	}
	$upload_path = "D:/phpstudy/WWW/.../static/uploadimages/"; //上传文件的存放路径
	//开始移动文件到相应的文件夹
	if(move_uploaded_file($file['tmp_name'],$upload_path.$file['name'])){
	  echo "Successfully!";
	}else{
	  echo "Failed!";
	}

猜你喜欢

转载自blog.csdn.net/qq_39835505/article/details/84986860