【发布时间】:2018-09-16 09:38:36
【问题描述】:
我有以下 Ajax 上传(来自cropper.js 的 Base64 画布数据),因此 Ajax 上传不是来自表单。
$('.gogo').on('touchstart mousedown', function(e){
e.preventDefault();
e.stopPropagation();
var img = new Array();
img[0] = fetchCrop1();
img[1] = fetchCrop2();
$.ajax({
cache: false,
type : 'POST',
url : 'http://localhost:3001/img',
data: { img : img },
contentType: false,
processData: false,
success : function(data) {
console.log('AJAX: '+data);
}
});
});
以及我见过的示例中的 Multer 脚本
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, '/img');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
app.post('/img',function(req,res){
var upload = multer({ storage : storage }).array('img',2);
upload(req,res,function(err) {
console.log(req.body);
console.log(req.files);
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
我已经阅读了许多帖子,但运气不佳,因为我不断将 req.body 和 req.files 设为 {} 和未定义。
我尝试了不同的 contentType 和单个上传,但显然我遗漏了一些东西,或者 JQuery Ajax 不适用于 Multer 多个文件?
我对 Node 比较陌生(LAMP 人),确实觉得 JavaScript 语法有点陌生。
我只想上传两张Base64图片到服务器/img文件夹。
我相信从cropper.js 中Base64 可以正常工作,下面是该函数的代码
function fetchCrop1(){
/* Note that images greater than 1000px are rejected by the server */
var $image = $('#image');
result = $image.cropper("getCroppedCanvas", "{ "width": 1000,
"height": 700 }", '');
$(document).find('#dataImg').val(result.toDataURL('image/jpeg'));
$('#dataImg').attr('value');
$('#download').attr('href', result.toDataURL('image/jpeg'));
return $('#dataImg').attr('value');
}
【问题讨论】:
-
multer 处理您没有发送也不需要发送的多部分/表单数据。我建议只使用 application/x-www-form-urlencoded 代替。
-
谢谢你,我最后做了什么。我确实尝试了使用 formData 并附加两个 blob 的解决方案,但也无法让它们以这种方式工作。
标签: jquery node.js ajax file-upload multer