सबसे पहले, आपको HTML
फॉर्म file input element के साथ बनाना चाहिए।
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="file" name="file">
<input type="submit" value="Submit">
</form>
तो आप express.bodyParser()
मिडलवेयर लोड होनी चाहिए::
app.use(express.bodyParser({uploadDir:'/path/to/temporary/directory/to/store/uploaded/files'}));
और फार्म पद संभालने के लिए एक मार्ग को परिभाषित: यहाँ एक सरल उदाहरण है
var path = require('path'),
fs = require('fs');
// ...
app.post('/upload', function (req, res) {
var tempPath = req.files.file.path,
targetPath = path.resolve('./uploads/image.png');
if (path.extname(req.files.file.name).toLowerCase() === '.png') {
fs.rename(tempPath, targetPath, function(err) {
if (err) throw err;
console.log("Upload completed!");
});
} else {
fs.unlink(tempPath, function() {
if (err) throw err;
console.error("Only .png files are allowed!");
});
}
// ...
});
अपलोड की गई फ़ाइल को दिखाने के लिए, मैं मान लीजिए कि आपके पास पहले से HTML
पृष्ठ है जिसमें एक छवि टैग है:
<img src="/image.png" />
अब आप res.sendFile
उपयोग कर सकते हैं अपलोड की गई छवि सेवा करने के लिए:
app.get('/image.png', function (req, res) {
res.sendfile(path.resolve('./uploads/image.png'));
});
पर एक नजर डालें पता करने के लिए सवालों की किस तरह किया जाना चाहिए [ 'FAQ'] (http://stackoverflow.com/faq) यहां पूछा वैसे भी, मैं इस बार आपके प्रश्न का उत्तर दूंगा। – fardjad