[英]How to serve image with http module as a file?
我建立了一個服務器來處理某種類型的請求(html和圖像文件)。
使用瀏覽器請求文件時,可以查看html文件或請求的圖像。
我也嘗試過建立一個客戶端腳本來請求文件。 當我請求html文件時,我可以正確接收它。
但是,當我請求圖像文件時,它已被接收,但是我無法查看圖像。
如何接收圖像作為文件?
服務器的相關路徑:
const server = http.createServer((req, res) => {
console.log(`${req.method} request for ${req.url}`);
console.log(`From: ${req.connection.remoteAddress}`);
let fileName = req.url;
if (utils.isFileExistsInDirectory(__dirname, fileName)) {
if (_.includes(fileName, '.html')) {
fs.readFile(`${__dirname}/${fileName}`, (err, data) => {
if (err) {
res.writeHead(400, {'Content-type':'text/html'});
res.end('A trouble occurred with the file.');
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
}
});
} else if (fileName.match(/.png$/)) {
fs.readFile(path.join(__dirname, 'images', fileName), (err, data) => {
if (err) {
res.writeHead(400, {'Content-type':'text/html'});
res.end('A trouble occurred with the file.');
} else {
res.writeHead(200, {'Content-Type': 'image/png'});
res.end(data);
}
});
} else {
fs.readFile(`${__dirname}/${fileName}`, (err, data) => {
if (err) {
res.writeHead(400, {'Content-type':'text/html'});
res.end('A trouble occurred with the file.');
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(data);
}
});
}
} else {
res.writeHead(404, {'Content-type':'text/html'});
res.end('File not found.');
}
});
客戶相關部分:
const req = http.request(options, res => {
let responseBody = '';
res.on('data', chunk => {
responseBody += chunk;
});
res.on('end', () => {
if (!fs.existsSync(`${__dirname}/${dir}`)){
fs.mkdirSync(`${__dirname}/${dir}`);
}
fs.writeFile(`${__dirname}/${dir}/${path}`, responseBody, err => {
if (err) {
throw err;
}
});
});
});
req.on('error', err => {
console.log(`problem with request: ${err}`);
});
req.end();
嘗試將圖像編碼為base64字符串
my.get("/getimg", function(req, res)
{
var img = new Buffer(data, 'base64');
res.writeHead(200, {
'Content-Type': 'image/png',
'Content-Length': img.length
});
res.end(img);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.