我正在使用express.js和multer将图像上传到服务器。我这样做:
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "../client/member/upload");
},
filename: function (req, file, callback) {
console.log('1', 1);
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
var upload = multer({ storage : storage}).single('userPhoto');
但问题是永远不会更改文件名。 我的上传程序处理程序:
function memberUpload(request, response) {
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "../client/member/upload");
},
filename: function (req, file, callback) {
console.log('1', 1);
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
var upload = multer({ storage : storage}).single('userPhoto');
var folderName = path.join(__dirname, '../', 'client/member/upload');
if (!fs.existsSync(folderName)) {
fs.mkdir(folderName, function (err) {
if (err) {
return response.status(500).send(err);
}
else {
upload(request, response, function (err) {
if (err) {
return response.status(400)
.send('No files were uploaded.');
}
var sentFile = request.files.file,
fileName = (request.files.file && request.files.file.name) ? request.files.file.name : 'test';
sentFile.mv(path.join(__dirname, '../', 'client/member/upload/', fileName), function (err) {
mime.lookup(path.join(__dirname, '../', 'client/member/upload/', fileName)); // => 'text/plain'
if (err) {
return response.status(500)
.send(err);
}
response.send({'location': '../member/upload/' + fileName});
});
});
}
});
}
else {
upload(request, response, function (err) {
if (err) {
return response.status(400)
.send('No files were uploaded.');
}
var sentFile = request.files.file,
fileName = (request.files.file && request.files.file.name) ? request.files.file.name : 'test';
sentFile.mv(path.join(__dirname, '../', 'client/member/upload/', fileName), function (err) {
mime.lookup(path.join(__dirname, '../', 'client/member/upload/', fileName)); // => 'text/plain'
if (err) {
return response.status(500)
.send(err);
}
response.send({'location': '../member/upload/' + fileName});
});
});
}
}
将文件保存到名为“blobid0.jpeg”,“blobid1.png”等的正确目录中...... 我的错是什么?
答案 0 :(得分:0)
这是我将任何文件(pdf,txt,png)上传到server.Hope的代码,这将对您有所帮助。
import time as t
t = t.time
starttime = t
def calcprod():
prod = 1
for i in range(1, 1000000):
prod = prod * i
p = calcprod()
print("The result is %s digits" % (str(len(p))))
endtime = t
print("It took %s seconds to calculate" % (starttime - endtime))