我正在尝试使用ajax将图像上传到nodejs服务器,但无法获取文件。
客户端
function sendFileToServer(file){
var formData = new FormData();
formData.append('profile_image',file,file.name);
$.ajax({
type: "POST",
url: "URL",
data: formData,
dataType:'json',
processData: false,
success: function (data) {
alert("Data Uploaded: "+data);
},
error : function(err){
alert(JSON.stringify(err));
}
});
}
$("#profile_image_2").change(function(){
var file = this.files[0];
sendFileToServer(file);
});
服务器端
var multer = require('multer');
var mime = require('mime-lib');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/upload/')
},
filename: function (req, file, cb) {
console.log("filename exte "+file.mimetype);
console.log(mime.extension(file.mimetype));
cb(null, Date.now() + '.' + mime.extension(file.mimetype)[0]);
//crypto.pseudoRandomBytes(16, function (err, raw) {
// cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype));
//});
}
});
var uploading = multer({ storage: storage });
router.post('/profile',uploading.single('profile_image') ,function(req,res){
if (req.file){
res.json("In here");
}else{
res.json("FILE DOES NOT EXIST");//ALWAYS ENDS UP HERE
}
});
当我以裸露的形式尝试时,它工作正常,但不使用ajax。请帮忙