在我的应用程序中,我只使用
app.use(express.json());
app.use(express.urlencoded());
Run Code Online (Sandbox Code Playgroud)
并不是
app.use(express.bodyParser());
Run Code Online (Sandbox Code Playgroud)
这样我就可以手动解析文件上传.看来这一行
app.use(passport.session());
Run Code Online (Sandbox Code Playgroud)
停止强制触发文件事件:
form.on('file', function(name, file) {
//never called
});
Run Code Online (Sandbox Code Playgroud)
如何使用护照会话而不与强大的文件事件发生冲突?
我有一个小功能正在运行,可以强大地接受传入的文件。它的工作原理就像一个魅力,但我在文档中看不到任何有关限制文件类型的内容。 https://github.com/felixge/node-formidable 似乎除此之外几乎所有其他内容都已涵盖。
还有其他人遇到过这个吗?
var form = new formidable.IncomingForm(),
files = [],
fields = [],
returnJson = {};
//setup the incoming
form.uploadDir = GLOBAL.server_settings.user_content;
form.encoding = 'utf-8';
form.maxFieldsSize = 2 * 1024 * 1024;
form.maxFields = 1000;
form.on('field', function(field, value) {
console.log(field, value);
fields.push([field, value]);
})
/* this is where the renaming happens */
.on ('fileBegin', function(name, file){
var fileType = file.type.split('/').pop();
//rename the incoming file
file.path = form.uploadDir + "/" + req.user.id + _ + toolbox.uniqid() + '.' + …Run Code Online (Sandbox Code Playgroud) 我在通过 api 路由上传文件时遇到了很多麻烦。
在客户端,我像这样提交文件:
onFormSubmit = (e) => {
e.preventDefault() // Stop form submit
this.fileUpload(this.state.file).then((response) => {
console.log('rD', response.data)
})
}
onFileChange = (e) => {
this.setState({ file: e.target.files[0] })
}
fileUpload = (file) => {
const url = '/api/mail/upload'
const formData = new FormData()
formData.append('file', file)
const config = {
headers: {
'X-CSRF-TOKEN': this.props.session.csrfToken
}
}
return axios.post(url, formData, config)
}
Run Code Online (Sandbox Code Playgroud)
我的请求/api/mail/upload是这样的:
Request Headers:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7
Connection: keep-alive
Content-Length: …Run Code Online (Sandbox Code Playgroud) 我在express3.x并使用强大的
app.post "/up",(req,res)->
formidable = require('formidable')
form = new formidable.IncomingForm()
form.uploadDir = __dirname + "/uploads"
form.encoding = 'binary'
form.addListener 'file',(name,file) ->
#write file
console.log('file uploaded')
return
console.log('$$$$$$$$$$$')
form.addListener 'end', ->
console.log('end')
res.end()
return
console.log('@@@@@$$$$')
form.parse req,(err,fields,files)->
console.log('parse')
console.log(err) if(err)
return
console.log('######')
return
Run Code Online (Sandbox Code Playgroud)
上传表格是
block content
:coffeescript
$ ->
formData = new FormData()
xhr = new XMLHttpRequest()
onProgress = (e)->
per_complete = (e.loaded/e.total) * 100 if e.lengthComputable
onReady = (e)->
alert("Ready")
onError = (err)->
alert("Error Loading "+err)
$('#upload').click (e)->
formData.append('img',document.getElementById('img').files[0])
xhr.open('post','/up',true) …Run Code Online (Sandbox Code Playgroud) 其实我遇到了两个问题
首先,如何更改上传路径
我的文件夹结构是这样的:
|__app.js
|__upload
Run Code Online (Sandbox Code Playgroud)
我的节点代码在app.js中并从中启动,所以我想上传图片上传到上传文件夹,我改变路径:
var form = new formidable.IncomingForm;
form.uploadDir = "./upload";
Run Code Online (Sandbox Code Playgroud)
它似乎上传成功,但我不知道文件去哪里,它不在上传文件夹中.
那么正确的路径名称是什么?
第二个问题是
如果我不更改它,它可以正确上传到它C:/Users/ADMINI~1/AppData/Local/Temp
但它将在没有foramt的情况下重命名,
那么如何才能获得上传格式并自行重命名?
第三个问题是
我还将处理程序绑定到process事件,例如
form.on('progress', function(bytesReceived, bytesExpected) {
console.log(bytesReceived + ' ' + bytesExpected);
});
Run Code Online (Sandbox Code Playgroud)
但似乎不起作用,上传日志时没什么.为什么?我错过了什么吗?
这是我的所有代码:
app.post('/upload', function (req, res) {
var form = new formidable.IncomingForm;
// form.uploadDir = "./upload";
console.log(form.uploadDir);
form.parse(req, function(err, fields, files){
if (err) return res.end('You found error');
console.log(files.image);
});
form.on('progress', function(bytesReceived, bytesExpected) {
console.log(bytesReceived + ' ' + bytesExpected);
});
form.on('error', function(err) {
res.writeHead(200, …Run Code Online (Sandbox Code Playgroud) 有许多关于文件上传的文章,教程和问题,但主要是针对初学者,没有一个完整地解释了如何保护文件上传以进行生产.我已经非常努力地找到关于如何做到这一点的完整答案,但它没有成功.
以下是我的发现的解释.
上传时限制文件大小:
app.use(express.limit('4mb'));
Run Code Online (Sandbox Code Playgroud)将文件上传限制为仅限某些路线:我无法将其实际工作,但这是我尝试过的:
更换:
app.use(express.bodyParser());
Run Code Online (Sandbox Code Playgroud)
同
app.use(express.json());
app.use(express.urlencoded());
Run Code Online (Sandbox Code Playgroud)
并将多部分中间件添加到每个上传路由:
app.post('/upload', express.multipart(), uploadController.uploadPhoto);
Run Code Online (Sandbox Code Playgroud)
这部分不起作用,但如果我离开,上传工作正常express.bodyParser().那么我做错了什么?
在保存上传到磁盘之前检查上载的文件类型:
我无法理解这一部分,但建议是编写一个自定义中间件,使用强大的内容来解析文件上传,并尝试在文件保存之前调整文件大小(假设它是图像),使用像图像魔术这样的库.建议这将使图像安全并确保它实际上是一个图像(因为如果它不是图像,该过程将失败).
这只适用于图像,因此它不是一个完整的解决方案.
我该如何实现呢?任何示例代码?
我上传的其他内容是否安全?
我正在使用 Express 4 和 Formidable 处理文件上传表单,但遇到了一些问题。
我想要实现的是:
-Check if file is selected and extension/format before file is uploaded to the server and abort if not .txt
-Write file "info" to db, copy file from tmp folder to dest. folder and delete tmp file.
Run Code Online (Sandbox Code Playgroud)
我的代码:
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.uploadDir = path.join(__dirname, '/uploads/tmp');
form.keepExtensions = true;
form.on('error', function(err) {
console.log(err.message);
req.flash('error', err.message);
res.redirect('/upload');
});
form.on('file', function(name, file){
var modname = file.path.split('/')[file.path.split('/').length-1]
var finals = path.join(__dirname, 'uploads/finals/' …Run Code Online (Sandbox Code Playgroud) 我使用强大的功能来处理NodeJs中的文件上传.我很难解析字段值.
如何获取project_id的值到表单处理程序,所以我可以在我的文件名中写入参数?
<input type="text" id="project_id" value="{{projects._id}}" readonly>
Run Code Online (Sandbox Code Playgroud)
编辑
更具体地说,这是我的表单上传处理的详细视图:
app.post('/uploads/', function (req, res){
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
res.writeHead(200, {'content-type': 'image/jpeg'});
res.write('received upload: \n\n');
var project = fields.project_id;
res.end(util.inspect(project, {fields: fields, files: files}));
});
form.on('end', function(project, fields, files){
console.log(project);
/*Temporary location of our uploaded file */
var temp_path = this.openedFiles[0].path;
/*The file name of the uploaded file */
var file_name = project + '.' + this.openedFiles[0].name;
Run Code Online (Sandbox Code Playgroud)
我可以登录var project的form.parse一部分.但我没有得到该form.on('end'...部分的变量. …
我正在使用 formidable 解析传入文件并将其存储在 AWS S3 上
当我调试代码时,我发现 formidable 首先将其保存到磁盘的 /var/folders/ 中,并且随着时间的推移,一些不必要的文件会堆积在磁盘上,这可能会导致以后出现大问题。
我在没有完全理解代码的情况下使用代码是非常愚蠢的,现在
我必须弄清楚如何在将解析的文件保存到 S3 后删除它,或者将其保存到 s3 而不将其存储在磁盘中。但问题是我该怎么做?
如果有人能指出我正确的方向,我将不胜感激
这就是我处理文件的方式:
import formidable, { Files, Fields } from 'formidable';
const form = new formidable.IncomingForm();
form.parse(req, async (err: any, fields: Fields, files: Files) => {
let uploadUrl = await util
.uploadToS3({
file: files.uploadFile,
pathName: 'myPathName/inS3',
fileKeyName: 'file',
})
.catch((err) => console.log('S3 error =>', err));
}
Run Code Online (Sandbox Code Playgroud) 我有一个 Node.JS 服务器作为路由器,可以向它发出 post 请求来上传文件,只允许 jpg/png/jpeg 扩展名,我目前正在做的是:
var form = new formidable.IncomingForm(),
files = [],
postToFolder,
source,
size = 0,
dest;
postToFolder = '/path/';
form.on('file', function (field, file) {
var fileType = file.type.split('/').pop();
if (fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg') {
// alot of stuff
}
else{
console.log('invalid filetype');
fs.unlinkSync(file.path);
console.log('Deleted: ' + file.path);
}
Run Code Online (Sandbox Code Playgroud)
此代码可以工作,但会将文件上传到 /tmp/ 文件夹,然后如果它们无效则必须将其删除。如果我可以在文件完全上传之前检查文件扩展名,那么性能会更好。有人知道怎么办吗?我尝试用谷歌搜索,但没有成功,并发现了一些不适用于 Formidable 的答案。
编辑:
所以我发现这个触发器在它开始之前就触发了,但它确实开始写入文件,取消它或破坏服务器,导致我的整个文件磁盘被写满几次,文档非常糟糕,所以我找不到任何东西将允许我“跳过”文件
form.on('fileBegin', function(field, file) {
var fileType = file.type.split('/').pop();
if (fileType == 'jpg' || …Run Code Online (Sandbox Code Playgroud) formidable ×10
node.js ×9
express ×6
file-upload ×5
asynchronous ×1
javascript ×1
next.js ×1
passport.js ×1
reactjs ×1