我的整个需求可以分解为下面几步:
step1.Node.js发送Buffer类型数据:
因为Node.js中fs文件系统读取文件后的回掉中均返回的为Buffer类型的数据,
直接通过queryString会使其数据丢失,故先采用JSON.stringify(chunk)对其进行
格式化,然后再通过queryString将其通过post发送请求出去。
代码如下:
var fs = require('fs');
var http = require("http");
var queryString = require("querystring")
// var filepath = "登陆注册.png";
var filepath = "mmp.txt";
var readSteam = fs.createReadStream(filepath);
readSteam.on("data",(chunk) => {
let chunkjson = JSON.stringify(chunk);
console.log(chunkjson);
let mydata = {"name":filepath, data: chunkjson};
doapost(mydata);
})
function doapost(data) {
let contents = queryString.stringify(data);
console.log("here");
console.log(contents);
let options = {
host: "localhost",
path: "/mytestpost/",
port: 8000,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': contents.length
}
};
let req = http.request(options, function (res) {
res.on("data", function (chunk) {
});
res.on("end", function (d) {
console.log("end")
});
res.on("error", function (e) {
console.log(e);
})
});
req.write(contents);
req.end();
}
step2.Django中通过bson.binary.Binary将其数据二进制化存入mongodb中:
代码如下
def mytestpost(request):
filename = request.POST['name']
data = request.POST['data']
# return HttpResponse(data)
client = pymongo.MongoClient('localhost', 27017)
db = client.cloudfiledb
coll = db.image
coll.save(dict(
content=bson.binary.Binary(bytes(data)),
filename='115.txt'
))
return HttpResponse(json.loads(data)["data"])
step3获取文件,请求该接口直接将该接口的返回chunk数据写入文件:
代码如下:
def getFile(request):
client = pymongo.MongoClient('localhost', 27017)
db = client.cloudfiledb
coll = db.image
data = coll.find_one({'filename':'115.txt'})
return HttpResponse(data['content'])
现在的问题是直接按上面的方式操作,写出来的文件内容为:
(因图片上传不了,我直接把图片内容贴出来)
{"type":"Buffer","data":[97,98,99,100,228,189,160,229,165,189]}
可以看出此数据即为上传时读取文件的chunk通过JSON.stringtify后的数据,也即就是bson.binary.Binary(bytes(data))中的data数据,而python中的bytes的构造函数也可接受python中的buffer类型
//~~~~
以下是 bytes 的语法:
class bytes([source[, encoding[, errors]]])
参数
如果 source 为整数,则返回一个长度为 source 的初始化数组;
如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;
如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;
如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。
如果没有输入任何参数,默认就是初始化数组为0个元素。
//~~
所以现在的问题就转化为如何在python中将Node.js中buffer通过JSON.stringtify的到的数据转化为python中的buffer类型的数据希望各位码友不吝赐教