//文件post发送
var express = require('express');
var router = express.Router();
var request = require("request");
var fs = require("fs");
fs.readFile("public/img/test.jpg", function (err, data) { if (err) { res.send({"errMsg":"'图片上传失败'"}); return; } var base64str = new Buffer(data).toString('base64'); //图片转字节 var mkJSON = { path: "public/upload", img: base64str, encoding: 'utf8' }; request({ url: "127.0.0.1:3000/img", method: "post", form: { mark: "IMG", content: JSON.stringify(mkJSON) } }, function (error, response, body) { if (!error && body != undefined && response.statusCode == 200 && body.indexOf("失败") < 0) { //fs.unlink(localPath); res.send({ success: true }); } else { console.log("err:" + body); res.send({"errMsg": "图片post失败", success: false}); } }); });
//post的文件进行接收
router.post("/img", function (req, res) { var content = req.param('content'); if (null != content) { var temp = JSON.parse(content); var mkJSON = temp[0]; var filePath = mkJSON.path.replace(/B//, ''); filePath = filePath.substr(0, filePath.lastIndexOf("/"));if (!err) { //目录创建成功 fs.writeFileSync(mkJSON.path.replace(/B//, ''), new Buffer(mkJSON.img.replace(/ /g, '+'), 'base64')); //res.json({"newImgPath": constClass.ip + "/image/" + mkJSON.path.replace(/B//, '')}); res.send('图片接收成功!'); } else { //目录创建失败 res.send('图片接收失败'); } } else { res.send('图片接收失败'); } });
thinkjs版:
async uploadAction() { let imgData = this.post("image"); let base64Data = imgData.replace(/^data:image/w+;base64,/, ""); let dataBuffer = new Buffer(base64Data, 'base64'); let imgpath = imgutil.getImageUrl("jpg"); let base64str = new Buffer(dataBuffer).toString('base64'); //图片转字节 console.log(imgpath); let mkJSON = { path: imgpath, img: base64str, encoding: 'utf8' }; let req = think.promisify(request.post); let reqObj = { url: think.config("makesite"), method: "post", form: { mark: "IMG", content: JSON.stringify(mkJSON) } }; let rs = await req(reqObj); if(rs != undefined && rs.statusCode == 200 && rs.body.indexOf("失败") < 0){ return this.success(think.config("imgsite")+imgpath); }else{ return this.fail(1,"图片上传出错"); } }