gpt4 book ai didi

javascript - 我如何使用 Node js上传文件?

转载 作者:行者123 更新时间:2023-11-30 12:47:57 25 4
gpt4 key购买 nike

我环顾四周,查看了有关如何使用 node/express 上传文件的各种教程。我觉得我在 HTML 或 JQuery 端做错了什么。我正在使用以下链接作为 http://howtonode.org/really-simple-file-uploads .

但是我得到了错误:

TypeError: Cannot read property 'fileUpload' of undefined    at module.exports.fileCreate 

下面是我的代码:

上传 Controller .js

fs.readFile(req.files.fileUpload.path, function (err, data) {
var newPath = __dirname + "/uploads/" + imgString;
fs.writeFile(newPath, data, function (err) {
});
});

html 片段

<div class="form-group">
<label for="fileUpload">Upload File</label>
<input type="file" name="fileUpload" id="fileUpload">
</div>

我正在使用 Sails 框架(不确定这是否会有所不同)

编辑:完成表格

<form role="form" class="uploadFileForm">
<div class="form-group">
<label for="fileTitleInput">Title</label>
<input type="text" name="formTitleInput" id="formTitleInput">
</div>
<div class="form-group">
<label for="fileDescriptionInput">Description</label>
<textarea class="form-control" rows="4" id="fileDescriptionInput"></textarea>
</div>
<div class="form-group">
<label for="fileUpload">Upload File</label>
<input type="file" name="fileUpload" id="fileUpload">
</div>
<button type="submit" class="btn btn-default" id="file-submit-btn">Publish to Web</button>
</form>

最佳答案

app.post('/upload', function(req, res) {

fs.readFile(req.files.image.path, function (err, data) {

var imageName = req.files.image.name

/// If there's an error
if(!imageName){

console.log("There was an error")
res.redirect("/");
res.end();

} else {

var newPath = __dirname + "/uploads/fullsize/" + imageName;

/// write file to uploads/fullsize folder
fs.writeFile(newPath, data, function (err) {

/// let's see it
res.redirect("/uploads/fullsize/" + imageName);

});
}
});
});

关于javascript - 我如何使用 Node js上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21926719/

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