node接收blob文件
emer 发布于 2020-8-11 17:19 2140 次阅读
上传base64的// base64转文件function dataURLtoFile(dataurl, filename) {var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);while (n--) {u8arr[n] = bstr.charCodeAt(n);}return new File([u8arr], filename, {type: mime});}// $.ajax({ // type: 'POST', // url: "/upload", // data: dataURLtoFile(image, 'aa.png'), // cache: false, // processData: false, // contentType: false, // success: function (ret) { // alert(ret); // } // }); formdata = new FormData(), xhr = new XMLHttpRequest(); formdata.append('fieldname',new Date().getTime()+'.png'); // 将文件添加到formdata对象中,(注:下面的file字段名在node中有用) formdata.append('file', dataURLtoFile(image, 'aa.png')); xhr.open("POST", "/upload", true); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { alert('ok') } } xhr.send(formdata);
app.post('/upload', function(req, res, next){ var ws = fs.createWriteStream("./index.png", { encoding: "binary" }); req.pipe(ws); res.send({ret_code: '0'}); });
或者:
var express = require('express'); var app = express(); var multer = require('multer') var fs=require('fs') app.use('/static',express.static('./static')); var storage = multer.diskStorage({ destination: function (req, file, cb) { cb(null, './upload') }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now()) } }) var upload = multer({ storage }); app.post('/upload',upload.single('file'), function(req, res, next){ // var ws = fs.createWriteStream("./index.png", { encoding: "binary" }); // req.pipe(ws); console.log(req.body) res.send({ret_code: '0'}); }); var server = app.listen(3000, function () { console.log('Example app listening on port 3000!'); });