base64的形式为“data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0。。。。”;
当接收到上边的内容后,需要将data:image/png;base64,这段内容过滤掉,过滤成:“iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0。。。”;然后进行保存。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
app.post(<span class="hljs-string">'/upload'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(req, res)</span></span>{ <span class="hljs-comment">//接收前台POST过来的base64</span> <span class="hljs-keyword">var</span> imgData = req.body.imgData; <span class="hljs-comment">//过滤data:URL</span> <span class="hljs-keyword">var</span> base64Data = imgData.replace(<span class="hljs-regexp">/^data:image\/\w+;base64,/</span>, <span class="hljs-string">""</span>); <span class="hljs-keyword">var</span> dataBuffer = <span class="hljs-keyword">new</span> Buffer(base64Data, <span class="hljs-string">'base64'</span>); fs.writeFile(<span class="hljs-string">"image.png"</span>, dataBuffer, <span class="hljs-function"><span class="hljs-keyword">function</span><span class="hljs-params">(err)</span> </span>{ <span class="hljs-keyword">if</span>(err){ res.send(err); }<span class="hljs-keyword">else</span>{ res.send(<span class="hljs-string">"保存成功!"</span>); } }); }); from:https://segmentfault.com/a/1190000005364299 |