微信小程序之图片文件上传

微信小程序之图片文件上传,第1张

选择图片: https://developers.weixin.qq.com/miniprogram/dev/api/media/image/wx.chooseImage.html

上传图片: https://developers.weixin.qq.com/miniprogram/dev/api/network/upload/wx.uploadFile.html

小程序身份认证脊谈界面,点击上传地方的加号,选择相册或者拍照,进行上传,原图无压缩,最多上传3张(分别为身份z正面、反面和手持)

注:这边以laravel框架为例

1、定义文件上传路由:

2、在laravel框樱缓碰架中的config文件夹下的filesystems.php文件中配置上传路径

3、身份认证文件上传方法

1、在身份认证界面的wxml中绑定选择图片事件

2、在身份认证界面的js中定义上传图片的方法

3、上传成功后,将上传的文哪液件地址存到数组中

本地图片,就搞个img,设置他的src就可以实卜则纯现;

参考如下:

<div class="column " style="width: 400pxmargin-left: 200px" id="imageShow">

<div id="productImageNew">@*用于图片预览*@

</div>

<div id="productImage">

<div class="widget the-common-margin-top" style="height: 400pxborder: 1px solid #eeeeee

padding: 3px">

<img id="imgHolder" style="max-height: 390pxmax-width: 390px" />

</div>

</div>

</div>

<form id="formImageUpload" name="formImageUpload" method="post" action="/DocTeam/ProductsImage/UploadImage"

enctype="multipart/form-data">

<div id="fileDiv">

<input type="file" id="theFile" name="theFile" size="20" style="cursor: pointer

width: 65pxheight: 60pxposition: absolutefilter: alpha(opacity:1)-moz-opacity: 0

opacity: 0z-index: 102" />

</div>

<input type="hidden" name="imageId_hide" id="imageId_hide" />

</form>

<div id="cover" style="position: absolutebackground-color: Whitez-index: 10

filter: alpha(opacity=100)-moz-opacity: 1opacity: 1overflow: autowidth: 400px">

<input id="selectImage" type="button" style="width: 65pxheight: 60px" value="Select" />

<br />

<br />

<input type="button" value="Upload" id="imageUpload" style="width: 65pxheight: 60px"

disabled="disabled"盯纤 onclick="javascript:uploadImage()" />

</div>

//js本地图型咐片预览,兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3

function PreviewImage(fileObj, imgPreviewId, divPreviewId) {

var allowExtention = ".jpg,.bmp,.gif,.png"//允许上传文件的后缀名document.getElementById("hfAllowPicSuffix").value

var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase()

var browserVersion = window.navigator.userAgent.toUpperCase()

if (allowExtention.indexOf(extention) >-1) {

if (fileObj.files) {//HTML5实现预览,兼容chrome、火狐7+等

if (window.FileReader) {

var reader = new FileReader()

reader.onload = function (e) {

document.getElementById(imgPreviewId).setAttribute("src", e.target.result)

}

reader.readAsDataURL(fileObj.files[0])

} else if (browserVersion.indexOf("SAFARI") >-1) {

alert("不支持Safari6.0以下浏览器的图片预览!")

}

} else if (browserVersion.indexOf("MSIE") >-1) {

if (browserVersion.indexOf("MSIE 6") >-1) {//ie6

document.getElementById(imgPreviewId).setAttribute("src", fileObj.value)

} else {//ie[7-9]

fileObj.select()

if (browserVersion.indexOf("MSIE 9") >-1)

fileObj.blur()//不加上document.selection.createRange().text在ie9会拒绝访问

var newPreview = document.getElementById(divPreviewId + "New")

if (newPreview == null) {

newPreview = document.createElement("div")

newPreview.setAttribute("id", divPreviewId + "New")

}

var a = document.selection.createRange().text

// newPreview.style.width = document.getElementById(imgPreviewId).width + "px"

// newPreview.style.height = document.getElementById(imgPreviewId).height + "px"

//newPreview.style.width = 390 + "px"

newPreview.style.height = 390 + "px"

newPreview.style.border = "solid 1px #eeeeee"

newPreview.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='" + document.selection.createRange().text + "')"

var tempDivPreview = document.getElementById(divPreviewId)

// tempDivPreview.parentNode.insertBefore(newPreview, tempDivPreview)

newPreview.style.display = "block"

tempDivPreview.style.display = "none"

}

} else if (browserVersion.indexOf("FIREFOX") >-1) {//firefox

var firefoxVersion = parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1])

if (firefoxVersion <7) {//firefox7以下版本

document.getElementById(imgPreviewId).setAttribute("src", fileObj.files[0].getAsDataURL())

} else {//firefox7.0+

document.getElementById(imgPreviewId).setAttribute("src", window.URL.createObjectURL(fileObj.files[0]))

}

} else {

document.getElementById(imgPreviewId).setAttribute("src", fileObj.value)

}

} else {

alert("仅支持" + allowExtention + "为后缀名的文件!")

fileObj.value = ""//清空选中文件

if (browserVersion.indexOf("MSIE") >-1) {

fileObj.select()

document.selection.clear()

}

fileObj.outerHTML = fileObj.outerHTML

}

}

function setTheFileButton_Cover_SelectImageButton() {

// debugger

// var position = $("#selectImage", "#cover").position()

// var css = { top: position.top, left: position.left }

// $("#theFile", "#fileDiv").css(css)

}

var $imgHolder = $('#imgHolder', "#productImage")

var tempDiv = $("#temp_div")

$("#select", "#cover").click(function () {

$("#theFile", "#fileDiv").click().select()

})

$("#theFile", "#fileDiv").click(function () {

$(this).blur()

})

$("#theFile", "#fileDiv").change(function () {

PreviewImage(this, 'imgHolder', 'productImage')

setTheFileButton_Cover_SelectImageButton()

// alert("预览已生成!")

$("#imageUpload").prop("disabled", false)

})

php实现上传图片保存到数据库的方法。具体分析如下:

php 上传图片,一般都使用move_uploaded_file方法保存在服务器上。但如果一个网站有多台服务器,就需要把图片发布到所有的服务器上才能正常使用(使用图片服务器的除外)

如果把图片数据保存到数据库中,多台服务器间可以实现文件共享,节省空间。

首先图片文件是二进制数据,所以需要把二进制数据保存在mysql数据库。

mysql数据库提供了BLOB类兄明型用于存储大量数据,BLOB是一个二进制对象,能容纳不同大小的数据。

BLOB类型有以下四种,除存储的最大信息量不同外,其他都是一样的。可根据需要使用不同的类型。

TinyBlob       最大 255B

Blob              最大 65K

MediumBlob  最大 16M

LongBlob      最大 4G

数据表photo,用于保存图片数据,结构如羡缓告下:

CREATE TABLE `photo` (  

  `id` int(10) unsigned NOT NULL auto_increment,  

  `type` varchar(100) NOT NULL,  

  `binarydata` mediumblob NOT NULL,  

  PRIMARY KEY  (`id`)  

) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 

upload_image_todb.php代码如下:

<?php  

// 连接数据库  

$conn=@mysql_connect("localhost","root","")  or die(mysql_error())  

@mysql_select_db('demo',$conn) or die(mysql_error()) // 判断action  

$action = isset($_REQUEST['action'])? $_REQUEST['action'] : '' 

// 上传图片  

if($action=='add'){  

    $image = mysql_escape_string(file_get_contents($_FILES['photo']['tmp_name']))  

    $type = $_FILES['photo']['type']  

    $sqlstr = "insert into photo(type,binarydata) values('".$type."','".$image."')"  

    @mysql_query($sqlstr) or die(mysql_error())  

    header('location:upload_image_todb.php')  

    exit()  

// 显示图片  

}elseif($action=='show'){  

    $id = isset($_GET['id'])? intval($_GET['id']) : 0  

    $sqlstr = "select * from photo where id=$id"  

    $query = mysql_query($sqlstr) or die(mysql_error())  

    $thread = mysql_fetch_assoc($query)  

    if($thread){  

        header('content-type:'.$thread['type'])  

        echo $thread['binarydata']  

        exit()  

    }  

}else{  

// 显示图片列表及上传表单哪哗  

?>  

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  

<html>  

 <head>  

  <meta http-equiv="content-type" content="text/html charset=utf-8">  

  <title> upload image to db demo </title>  

 </head>  

  

 <body>  

  <form name="form1" method="post" action="upload_image_todb.php" enctype="multipart/form-data">  

  <p>图片:<input type="file" name="photo"></p>  

  <p><input type="hidden" name="action" value="add"><input type="submit" name="b1" value="提交"></p>  

  </form>  

  

<?php  

    $sqlstr = "select * from photo order by id desc"  

    $query = mysql_query($sqlstr) or die(mysql_error())  

    $result = array()  

    while($thread=mysql_fetch_assoc($query)){  

        $result[] = $thread  

    }  

    foreach($result as $val){  

        echo '<p><img 

src="upload_image_todb.php?action=show&id='.$val['id'].'&t='.time().'"

 width="150"></p>'  

    }  

?>  

</body>  

</html>  

<?php  

}  

?>

程序运行截图和数据库截图:


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12417440.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存