小程序圖片轉(zhuǎn)成base64的實(shí)現(xiàn)方式
2020-09-27|HiShop
導(dǎo)讀:目前,小程序圖片或者本地文件轉(zhuǎn)成base64是不能夠?qū)崿F(xiàn)的,以下是具體分析:...
目前,小程序圖片或者本地文件轉(zhuǎn)成base64是不能夠?qū)崿F(xiàn)的,以下是具體分析:
微信小程序wx.uploadfile, 利用PHP接口把本地圖片轉(zhuǎn)化為base64流.
網(wǎng)上到處都是粘貼復(fù)制的wx.uploadfile的解決方案, 但目前還沒有具體的代碼:
特意呈現(xiàn)出來給需要的伙伴們:
代碼:
<pre name="code" class="php">case 'imgBufferToBase64':
<span style="white-space:pre"> </span>$data='';
<span style="white-space:pre"> </span>file_put_contents("1.txt",var_export($_FILES,true)."\r\n",FILE_APPEND);
<span style="white-space:pre"> </span>if(!empty($_FILES['upload']['tmp_name'])){
<span style="white-space:pre"> </span>if(empty($_FILES['upload']['type'])){
<span style="white-space:pre"> </span>IO::Debug('文件類型不合法');
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>if(!in_array($_FILES['upload']['type'],array(
<span style="white-space:pre"> </span>'image/gif',
<span style="white-space:pre"> </span>'image/pjpeg',
<span style="white-space:pre"> </span>'image/jpeg',
<span style="white-space:pre"> </span>'image/x-png',
<span style="white-space:pre"> </span>'image/png',
<span style="white-space:pre"> </span>'image/bmp'
<span style="white-space:pre"> </span>))){
<span style="white-space:pre"> </span>IO::Debug($_FILES['upload']['type'].'文件類型不合法');
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>$data=file_get_contents($_FILES['upload']['tmp_name']);
<span style="white-space:pre"> </span>file_put_contents("1.txt",var_export($data,true)."\r\n",FILE_APPEND);
<span style="white-space:pre"> </span>IO::Debug('解析成功',true,$data);
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>IO::Debug("解析失敗");
break;
</pre>
<pre></pre>
<p></p>
<pre></pre>
<span style="font-size:14px">js代碼:</span>
<p></p>
<pre name="code" class="javascript">wx.uploadFile({
url: 'https://' + app.globalData.host + '/api/?sign=' + sign,
filePath: tempFilePaths[0],
name: 'upload',
header: {
"content-type": "multipart/form-data",
"content-type": "application/x-www-form-urlencoded"
},
formData: formData,
success: function (res) {</pre><pre name="code" class="javascript"><span style="white-space:pre"> </span>var $data = JSON.parse(res.data);</pre><pre name="code" class="javascript"> if (typeof ($data.data) != "undefined" && $data.code){
var imgBase64 = "data:image/jpeg;base64," + $data.data;
}
}
})</pre><br data-filtered="filtered">
<p></p>
<p><br data-filtered="filtered">
</p>
<span style="font-size:14px"><br data-filtered="filtered">
<br data-filtered="filtered">
</span>
<p></p>
<pre></pre>
HiShop小程序工具提供多類型商城/門店小程序制作,可視化編輯 1秒生成5步上線。通過拖拽、拼接模塊布局小程序商城頁面,所看即所得,只需要美工就能做出精美商城。
更多小程序開發(fā)案例,盡在:http://m.descansotropical.com/xiaocx/kaifa.html