我的cgi脚本在具有Firefox和Chrome浏览器的Linux系统上如下:假设它只是一个PDF文件。我还需要在浏览器中显示图像文件。无法追踪错误。
#! /usr/bin/env python
###################################################
# File should be searched on server and displayed
# in the browser
###################################################
import cgi
import cgitb
cgitb.enable()
import StringIO
import sys
import os,glob
import subprocess
import webbrowser
def check_file_extension(display_file):
input_file = display_file
nm,file_extension = os.path.splitext(display_file)
return file_extension
print "Content-type: text/html\n"
responseStr = "<html> %s </html>"
print "<pre>"
form = cgi.FieldStorage()
webbrowser.open_new_tab("file:///home/Documents/postgresql.pdf")
file_nm = ''
nm =''
path = '/home/Documents'
not_found = 0
if form.has_key("file1"):
file_nm = form["file1"].value
for f in next(os.walk(path))[2]:
if str(f) == str(file_nm).strip():
not_found = 0
print 'Found file: ' + f
type_of_file = check_file_extension(f) #TODO: Based on extension, change content type headers for display
absolute_path_of_file = os.path.join(path, f)
file_url = 'file://'+absolute_path_of_file
print '<a href='+file_url+'>'+ absolute_path_of_file+'</a>'
try:
pdf1 = open(absolute_path_of_file,'rb').read()
print "Content-type: application/pdf\n"
print pdf1
break
except Exception,e:
print e
else:
not_found = 1
if not_found == 1:
print "%s" % str(file_nm) + " not found"
print "%s" % file_nm
print "</pre>"
答案 0 :(得分:0)
我编辑了我的代码以这种方式工作:
#! /usr/bin/env python
import os
import cgi
import cgitb
cgitb.enable()
import sys
def check_file_extension(display_file):
input_file = display_file
nm,file_extension = os.path.splitext(display_file)
return file_extension
form = cgi.FieldStorage()
type_of_file =''
file_nm = ''
nm =''
path = '/home/shantala/Documents'
not_found = 0
if form.has_key("file1"):
file_nm = form["file1"].value
for f in next(os.walk(path))[2]:
if str(f) == str(file_nm).strip():
not_found = 0
absolute_path_of_file = os.path.join(path, f)
type_of_file = check_file_extension(absolute_path_of_file)
if type_of_file == '.pdf':
file_read = file(absolute_path_of_file,'rb').read()
print 'Content-type: application/pdf\n'
print file_read
if type_of_file == '.txt':
file_read = file(absolute_path_of_file,'rb').read()
print 'Content-type: text/html\n'
print file_read
if type_of_file == '.png':
file_read = file(absolute_path_of_file,'rb').read()
print 'Content-type: image/png\n'
print file_read
if type_of_file == '.pdf':
file_read = file(absolute_path_of_file,'rb').read()
print 'Content-type: application/pdf\n'
print file_read
if type_of_file == '.JPG':
file_read = file(absolute_path_of_file,'rb').read()
print 'Content-type: image/jpg\n'
print file_read
if type_of_file == '.bmp':
file_read = file(absolute_path_of_file,'rb').read()
print 'Content-type: image/bmp\n'
print file_read
break
else:
not_found = 1
if not_found == 1:
pass
# print "%s" % str(file_nm) + " not found"