用nodejs处理文件上传(2)

在(1)中我们将文件上传到服务器,本节要实现在浏览器中显示上传后的图片。
1 改写处理器的上传处理逻辑
function upload(response,request) {
console.log("Request handler 'upload' was called.");

var form = new formidable.IncomingForm();
console.log("about to parse");
form.parse(request, function(error, fields, files) {
console.log("parsing done");
/* windows系统下可能出错,所以对上传的文件重命名*/
fs.rename(files.upload.path, "/tmp/test.png", function(error) {
if (error) {
fs.unlink("/tmp/test.png");
fs.rename(files.upload.path, "/tmp/test.png");
}
});
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:<br/>");
response.write("<img src='/show' />");
response.end();
});
}

windows和linux对上传文件的保存位置处理方式不一样,为统一起见,我们将对上传的文件路径进行改写使之一致。
此处利用的nodejs的fs模块fs.rename(files.upload.path, "/tmp/test.png")
2 新增处理器显示函数
function show(response) {
console.log("Request handler 'show' was called.");
response.writeHead(200, {"Content-Type": "image/png"});
fs.createReadStream("/tmp/test.png").pipe(response);
}

首先要设置content-type为image/png,然后调用fs模块的方法将其推送到前台。
3 当浏览器请求路径为/show的时候,我们把图片信息推送到前台进行显示。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值