在Node.js入门书中最后部分。我们上传了照片,然后现在照片,假如我们上传了照片,照片的名字不是test.png,而是照片本身的名字。那在show函数中怎么去显示这张照片呢
就是怎么从upload中传递照片名字给show函数
下面是我的代码
function upload(response, request){
console.log("Request handler 'upload' was called ... ");
// using formidable
var form = new formidable.IncomingForm();
// set form encoding as utf-8
form.encoding = "utf-8";
var path = process.cwd();
if("win32" == process.platform){
path += "\\tmp\\";
} else {
path += "/tmp/";
}
console.log("Current Work Directory -> " + process.cwd());
console.log("Current Operator System -> " + process.platform);
console.log("Current File Path -> " + path);
// set default upload folder
form.uploadDir = path;
console.log("about to parse ... ");
form.parse(request, function(error, fields, files){
console.log("parsing done ... ");
var filename = files.upload.name;
console.log("filename = " + filename);
try{
fs.renameSync(files.upload.path, path + filename);
}catch(e){
console.log("Rename Exception --> " + e);
}
response.writeHead(200, {"Content-Type": "text/html"});
response.write("received image:<br/>");
response.write("<img src='/show' />"); // send show request
response.end();
})
}
function show(response){
console.log("Request handler 'show' was called ... ");
fs.readFile("./tmp/test.png", "binary", function(error, file){
if(error){
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(error + "\n");
response.end();
}else{
response.writeHead(200, {"Content-Type": "Image/png"});
response.write(file, "binary");
response.end();
}
});
}
不好意思,完全没有web编程的概念,请教了。。。。
5 回复
这个…………入门书没看 但是好像你贴上来的代码已经是两次http请求了?upload返回了 浏览器会再次提交请求到show(response)………………你如果要filename的话,最简单的可以在upload中返回的img路径里把filename作为下次请求的参数,然后在function show里面读出来
我没注意,贴上去的标签被转义了…………
首先你要清楚 你上面两个 function,一个是upload,一个是show,nodejs我不熟,按照一般的理解你的代码先执行了upload,返回了html
response.write("<img src='/show' />"); // send show request
给浏览器,实际上是浏览器收到html后又请求了 show这个路径,然后后台才会再调用你的function show ,不知道这样说你清楚了没
在function upload里你可以直接把filename 作为对show请求的一个参数再传回来,
response.write("<img src='/show?filename="+filename+"' />"); // send show request
然后由function show解析,其他的方式可以用cookie\session之类的
我真不适应markdown………………