gpt4 book ai didi

javascript - Node.js + ajax,上传文件

转载 作者:行者123 更新时间:2023-11-30 09:28:24 25 4
gpt4 key购买 nike



我一直在尝试使用 node.js 和 ajax 上传文件,但我无法让它工作。我没有收到错误,但我的存储文件夹中没有任何内容。

index.js:

app.post('/newFlavour', function(req, res){
console.log("[INFO] New flavour request: " + req.body.name);

let form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, '/storage');

form.on('file', function(field, file) {
fs.rename(file.path, path.join(form.uploadDir, file.name));
});

form.on('error', function(err) {
console.log('An error has occured: \n' + err);
});

form.on('end', function() {
console.log('success');
});

form.parse(req); });

我的ajax请求函数:

function createFlavour() {
let file = $('#upload-input').get(0).files;
const formData = new FormData();
formData.append('uploads', file, file.name);

console.log(file)

$.ajax({
url: "http://localhost:3000/newFlavour",
type: "POST",
dataType: "json",
data: JSON.stringify({
name: $('#name').val(),
file: file
}),
contentType: "application/json",
success: function (data) {
console.log(data);
},
error: function () {
alert("Error occured");
},
complete: function () {
console.log("complete")
}
});

clearModal(); }

输入标签:

<input id="upload-input" type="file" name="upload"></br>

我不知道我在这里错过了什么。

提前致谢!

最佳答案

您应该在开始时解析您的req。同样根据 formidable documentation

fileBegin

Emitted whenever a new file is detected in the upload stream. Use this event if you want to stream the file to somewhere else while buffering the upload on the file system.

form.on('fileBegin', function(name, file) { });

这样做应该可以保存你的文件

app.post('/newFlavour', function (req, res){
var form = new formidable.IncomingForm();

form.parse(req);

form.on('fileBegin', function (name, file){
file.path = __dirname + '/storage/' + file.name;
});

form.on('file', function (name, file){
console.log('Uploaded ' + file.name);
});

res.status(200);
});

另外你的ajax Post是错误的,这应该可以工作

    var data = new FormData();
$.each($('#upload-input')[0].files, function(i, file) {
data.append('file-'+i, file);
});

$.ajax({
url: 'http://localhost:3000/newFlavour',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
});

关于javascript - Node.js + ajax,上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47890587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com