gpt4 book ai didi

node.js - 如何重命名由 Formidable 解析的文件?

转载 作者:IT老高 更新时间:2023-10-28 23:09:01 24 4
gpt4 key购买 nike

如何在 Node 中命名由 Formidable 解析的文件?目前我的文件保存为“7c9d182a9892bb7588b49ea9d364efd0.pdf”,我更喜欢原始文件名。

有人知道怎么做吗?

最佳答案

我就是这样做的(查看 .on(file'...) 函数):

// import required modules
var express = require('express');
var formidable = require("formidable"); // used for parsing form data
var fs = require('fs');

// prevent bodyParser from handling multipart forms (ie only handle get and post requests)
delete express.bodyParser.parse['multipart/form-data'];

// create server
var app = express.createServer();

// connect middleware
app.configure(function() {
// creates body object on request object
app.use(express.bodyParser());
app.use(express.methodOverride());
// used to display static files such as css
app.use(express.static(__dirname + '/static'));
});

// enable and define views
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');

//******************************
//* create routes
//******************************

// file upload handling
app.get('/photos/new', function(request, response) {
response.render('photos/new');
});
app.post('/photos', function(request, response) {
console.log('in /photos handler');
var form = new formidable.IncomingForm();

form.uploadDir = __dirname + '/static/upload/photos/';

form.on('file', function(field, file) {
//rename the incoming file to the file's name
fs.rename(file.path, form.uploadDir + "/" + file.name);
});

form.on('error', function(err) {
console.log("an error has occured with form upload");
console.log(err);
request.resume();
});

form.on('aborted', function(err) {
console.log("user aborted upload");
});

form.on('end', function() {
console.log('-> upload done');
});

form.parse(request, function() {
response.render('photos/new');
});
});

// start our server
app.listen(8888);

关于node.js - 如何重命名由 Formidable 解析的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8359902/

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