我正在尝试像上传文件一样使用
node js
使用
multer
节点插件。
server.js代码
服务器.js
var express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var PORT = process.env.PORT || 3000;
// use of body parser
app.use(bodyParser.json());
app.use(cors());
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1])
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
app.post('/upload', function (req, res) {
upload(req, res, function (err) {
if (err) {
res.json({error_code: 1, err_desc: err});
return;
}
res.json({error_code: 0, err_desc: null});
});
});
app.listen(PORT, () => {
console.log(`App is listening to ${PORT}`);
})
这里也有代码
https://repl.it/repls/LustrousCharmingCommunication
这是我使用jquery的客户端
客户端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="fileUploadForm">
<input type="file" name="file" id="fileId"/>
<input type="submit" value="Upload" name="submit" class="submit">
label <input type="text" placeholder="enter first name"/>
</form>
<script src="../node_modules/jquery/dist/jquery.js"></script>
</body>
<script>
$(function () {
$('.submit').on('click', function (e) {
e.preventDefault();
e.stopPropagation();
if ($('#fileId').val().length === 0) {
alert('please insert file')
} else {
var form = $('#fileUploadForm')[0];
// Create an FormData object
var data = new FormData(form);
$.ajax({
url: 'http://localhost:3000/upload',
type: 'POST',
data: data,
cache: false,
enctype: 'multipart/form-data',
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function (data, textStatus, jqXHR) {
if (typeof data.error === 'undefined') {
// Success so call function to process the form
}
else {
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
}
})
})
</script>
</html>
这里也有代码
https://jsbin.com/luwezirive/edit?html,js,output
为什么文件未上载到
uploads
文件夹?我想上传附件,点击