javascript - 如何点击发布请求,以便上传的文件保存在某个位置
问题描述
我正在尝试node js
使用multer
节点插件上传类似文件。server.js 代码
server.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,输出
为什么文件没有上传到uploads
文件夹中?我想点击按钮上传附件
解决方案
推荐阅读
- elasticsearch - How to create a new instance with existing deployments in google cloud
- python - Flask block 'content' defined twice
- javascript - validate css properties without selector using CSSLint module Javascript
- sql - 具有不同条件的多个 SELECT 查询
- ruby-on-rails - 从 Rails 3 到 4 了解 Pundit 的货币补丁实现
- r - 对数据框进行排序
- excel - Vba 代码防止删除包含公式的单元格
- python - 通过数据框计算循环
- opengl - 附加几何着色器时着色器未链接OpenGL
- python - 如何在 MongoDB/PyMongo 中进行一对多查询