本文介绍了如何在KeystoneJS中上传S3文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为style的项目,该项目具有2个属性,一个具有原始CSS文本,另一个具有 S3File .
I have an item called style which has 2 attributes, one which has raw css text and another which has an S3File.
Style.add({
...
css: { type: Types.Code, language: 'css' },
cssFile: {
type: Types.S3File,
s3path: 'uploads/assets',
},
...
});
我想用CSS文本的内容更新 S3File ./p>
I want to update the S3File with the contents of the css text.
function uploadCSStoAmazon(style) {
// Store css code in temporal file (with a md5 name)
var rndm = crypto.randomBytes(20).toString('hex'), file_path = '/tmp/css_temp_' + rndm + '.css';
fs.writeFile(file_path, style.css, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
// style.cssFile = new Types.S3File();
// TODO upload file to amazon
style.cssFile._.uploadFile(file_path, true, function(err, fileData){
// TODO erase css file
});
});
}
...
var aStyle = new Style.model({
...
css: 'Some css string',
...
});
...
uploadCSStoAmazon(aStyle);
我了解cssFile属性是未定义的,但是我如何创建一个新文件并将其分配给该属性,并上传该文件呢?
The cssFile attribute is undefined, I understand, but how could I create a new file and assign it to this attribute, and also upload the file?
推荐答案
我发现了如何使用Keystone随附的updateHandler.他们仍然使用express.x格式的req.files.
I found out how, you can use the updateHandler that comes with Keystone. They're still using req.files form express 3.x though.
// A express file generator
function writeToFile(fileName, txt, ext, callback) {
var rndm = crypto.randomBytes(20).toString('hex'), file_path = '/tmp/css_temp_' + rndm + '.' + ext, the_file = {};
fs.writeFile(file_path, txt, function(err) {
if(err) {
callback(null, err);
}
var stats = fs.statSync(file_path);
var fileSizeInBytes = stats["size"];
the_file.path = file_path;
the_file.name = fileName + '.' + ext;
the_file.type = 'text/' + ext;
the_file.size = fileSizeInBytes;
console.log("The file was cached!");
callback(the_file, err);
});
}
...
/**
* Update Style by ID
*/
exports.update = function(req, res) {
var data = (req.method == 'POST') ? req.body : req.query;
Style.model.findById(data._id).exec(function(err, item) {
if (err) return res.apiError('database error', err);
if (!item) return res.apiError('not found');
writeToFile(item.slug, data.css, 'css', function(req_file, err){
if (err) return res.apiError('update error during file cache', err);
req.files['cssFile_upload'] = req_file;
item.getUpdateHandler(req).process(data, function(err) {
if (err) return res.apiError('update error', err);
res.apiResponse({
success: true
});
}); // end process
}); // end writeToFile
});
};
这篇关于如何在KeystoneJS中上传S3文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!