我一直致力于NodeJS中的文件上传,我一直很难上传jQuery文件。我收到了CORS错误。我按照S3 here
上的文件上传教程进行了操作我正在使用s3fsImpl
s3
s3fs
这是我的路线
router.post('/', isAuthenticated, function(req, res, next) {
// Check for mandatory form data to be filled
// isAuthenticated has an auth-token in the header
var auth_token = req.headers['auth-token'];
// I believe req.files.file is not getting the file itself
if (req.files.file) {
var file_name = req.files.file;
var stream = fs.createReadStream(file_name.path);
if (file_name) {
return s3fsImpl.writeFile(file_name.originalFilename, stream).then(function() {
fs.unlink(file_name.path, function(err) {
if (err) {
console.error(err);
} else {
res.json({"status": 200, "message":"file uploaded"});
// res.end();
}
});
}); // callback ends here
}
} else {
res.status(400);
res.json({
'status': 400,
'message': 'bad request, missing fields'
});
res.end();
}});
这是JQuery Ajax POST
$('#uploadAction').click(function() {
uploadVal = $('#my-file').val();
var res = $('input[type=file]')[0].files[0].name;
console.log(res);
var settings = {
async: true,
crossDomain: true,
url: "my_url",
method: 'POST',
headers: {
'auth-token': 'my_auth_token'
},
processData: false,
dataType: 'form-data',
data: {'file': res},
success: function(data) {
$('#statusMsgs').css('background', 'green');
$('#statusMsgs').text('File Successfully Uploaded!');
},
error: function(jqXhr, textStatus, errorThrown) {
//var obj = JSON.parse(responseText.responseText);
$('#statusMsgs').text(textStatus);
}
};
$.ajax(settings);
});
我还添加了
app.use(function(req, res, next) {
// res.header('Access-Control-Allow-Headers', 'Origin,X-Requested-With,content-type,Authorization,auth-token,Accept');
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST');
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization,auth-token');
next();
});
这是HTML部分
<input type="file" name="my_file" id="my-file" style="border: 1px solid #ccc; padding: 6px;">
<a href="#" id="uploadAction" style="background: #2D86C2; padding: 10px; color: #fff; text-decoration: none;">Upload</a>