HTML code:
<form enctype="multipart/form-data">
<input id="upFile" class="upFile" type="file"
size="0" name="file" accept="image/gif,image/jpeg,image/png">
<input type="submit" id="upFileBtn" class="upFile">
</form>
Ajax code: result:success
$('#upFileBtn').click(function () {
var file = $('#upFile');
var formData = new FormData();
formData.append('file',file[0]);
$.ajax({
url: '/api/upload',
type: 'post',
data: formData,
// async: false,
cache: false,
contentType: false,
processData: false,
success: function(data){
if(200 === data.code) {
$('#upFile').val('');
alert('success');
} else {
alert("failed");
}
},
error: function(){
alert("wrong");
}
});
});
API:
var express = require('express');
var router = express.Ro
router();var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, config.upload)// upload:"./public/uploads"
},
filename: function (req, file, cb) {
cb(null,file.originalname)
}
});
var upload = multer({ storage: storage });
//upload
router.post('/upload', upload.single('file'), function (req, res, next) {
console.log(req.file);//undefined
});
I can't find out what's wrong. I hope that req.file
existed, but it wasn't.
I found the directory('public/uploads'
),b ut it doesn't have any pictures.
The Ajax code had run alert('success'), I guess that multer did't save image or didn't get the images. But I saw the network request has send the image. So who can tell me what's wrong with it?