【发布时间】:2018-08-16 16:51:19
【问题描述】:
您能告诉我如何将文件上传到当前示例的某个目录(uploads 文件夹)。这是我的服务器端代码
app.post('/upload', function (req, res) {
console.log('abcc')
upload(req, res, function (err) {
if (err) {
res.json({error_code: 1, err_desc: err});
return;
}
res.json({error_code: 0, err_desc: null});
});
});
完整的代码节点js https://repl.it/repls/LustrousCharmingCommunication
我使用此服务器并使用客户端访问服务并仅上传附件
这是我的请求客户端代码 https://jsbin.com/luwezirive/edit?html,js,output
$(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);
console.log('fffff')
$.ajax({
url: 'https://lustrouscharmingcommunication--five-nine.repl.co/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) {
console.log('succsss');
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
}
});
}
})
})
我成功了,但是文件没有上传,为什么?
上传方式
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');
有什么更新吗?
【问题讨论】:
-
你的
upload()方法是什么? -
我看到的第一个问题是
var form = $('#fileUploadForm')[0];。用Id选择元素不会给你一个数组。所以,把它改成var form = $('#fileUploadForm'); -
@GeorgeBailey 不,这不是一个数组,这是一个 jQuery 对象,访问索引 0 将为您提供与集合中第一个元素对应的 DOM 对象。这不是错误:-)
-
@GeorgeBailey 等于
var form = document.getElementById('fileUploadForm');或var form = document.querySelector('#fileUploadForm');。 -
请向我们展示您的
upload()方法!
标签: javascript jquery node.js multer