#! /usr/bin/python2
# coding=utf-8
from jinja2 import Environment, PackageLoader
import socket
import time, datetime, re
import os
import hashlib, urllib, json
#from datetime import datetime
global listen_socket
_COOKIE_KEY = 'AwEsOmE'
UPLOAD_FOLDER = 'upload'
basedir = os.path.abspath(os.path.dirname(__file__)) # 获取当前项目的绝对路径
ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'xlsx', 'gif', 'GIF']) # 允许上传的文件后缀
# 判断文件是否合法
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
def getfile():
print (os.getcwd())
path1=os.path.join(os.getcwd(), 'uploadfile')
print "111",path1
flist=os.listdir(path1)
print (os.getcwd()), flist
return flist
def isHavefile(filename):
print (os.getcwd())
path1=os.path.join(os.getcwd(), 'uploadfile', filename)
flag=os.path.isfile(path1)
print (os.getcwd()), flag, "xxx"
return flag
#下载要下载的文件,要下载的文件是通过get方法来传递的
def fun():
global listen_socket
global g_user
_COOKIE_NAME = 'awesession'
http_response = '''HTTP/1.x 200 OK\nContent-Type: text/html; charset=utf-8; \n\n'''
print "g_user"
while True:
conn, client_address = listen_socket.accept()
#request = conn.recv(1024)
request = ''
buffer_size = 1024
while 1:
time.sleep(0.9)
data = conn.recv(buffer_size).decode('utf-8')
request += data
print "len",len(data)
if len(data) < buffer_size:
break
print "yanshi"
print "re--", len(request), request
if request == "":
print "requrest null"
continue
method = request.split(' ')[0]
src = request.split(' ')[1]
print "-method----------------------------------------------------", method, src
g_user = None
try:
cookie = request.split("Cookie:")[1].split("\r\n")[0]
except:
print "cookie null"
'''
<head>
<title>WOWzh</title>
</head>
<html>
<p>Wow, Pythond 说的Sserver</p>
</html>
'''
if method == 'GET':
# ULR
print "-----get src--------",src
file_name = src[1:len(src)]
print "-----file_name--------", file_name
#if src == '/test.jpg':
if -1 != src.find("/static/css/"):
print "static--dir"
content = read_file(file_name, "text/css")
elif -1 != src.find("/download/"):
print "download--dir"
content = read_file(file_name, "text/css")
else:
file_name = "upload2.html"
with open("./templates/upload2.html","rb") as f:
output = f.read()
# print output
content = http_response + output
print 'Connected by', client_address
print 'Request is:', request
#print 'content is:', content
conn.sendall(content)
elif method == 'POST':
if -1!= src.find("/api/upload"):
http_response2 = '''HTTP/1.x 200 OK\nContent-Type: application/json; charset=utf-8\n\n'''
form = request.split('\r\n')
print "form----", form
idx = form.index('') + 1 # Find the empty line
print "idx----", idx
entry = form[idx:] # Main content of the request
print "entry----", entry, type(entry)
body = request.split('\r\n\r\n')
for b in body:
print "bb",body.index(b), b
print "body",body
body_last=body[len(body)-1]
body_last2=body[len(body)-2]
print "body last", body_last, body_last2
file_dir = os.path.join(basedir, UPLOAD_FOLDER) # 拼接成合法文件夹地址
print "file_dir",file_dir
if not os.path.exists(file_dir):
os.makedirs(file_dir) # 文件夹不存在就创建
print "req",request
print "files",request
f = request # 从表单的file字段获取文件,myfile为该表单的name值
boundary = f.split("boundary=")[-1].split("\r\n")[0]
filename = f.split("filename=")[-1].split("Content-Type")[0].strip('\r\n').replace("\"","")
print "leixing",type(boundary),boundary,filename,type(filename), len(filename)
str_b = "--" + boundary + "--"
body_last = body_last.replace(str_b, "")
print "body_last",body_last
#'''
if f and allowed_file(filename): # 判断是否是允许上传的文件类型
fname = filename
ext = fname.rsplit('.', 1)[1] # 获取文件后缀
unix_time = int(time.time())
new_filename = str(unix_time) + '.' + ext # 修改文件名
print "dirr",file_dir, new_filename
with open(os.path.join(file_dir, new_filename),"wb") as f:
f.write(body_last)
# 保存文件到upload目录
str1 = http_response2 + json.dumps(
dict(error='0', errmsg='上传成功'))
else:
str1 = http_response2 + json.dumps(
dict(error='1001', errmsg='上传失败'))
#'''
#str1 = http_response2 + json.dumps(
# dict(error='1001', errmsg='上传失败no'))
else:
str1 = ""
print "str1--------------api-auth",str1
conn.sendall(str1)
######
# More operations, such as put the form into database
# ...
######
elif method == 'PUT':
print "-----PUT src--------", src
elif method == 'DELETE':
print "-----DELETE src--------", src
# close connection
conn.close()
def init_web():
global listen_socket
HOST, PORT = '', 8888
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(10)
print 'Serving HTTP on port %s ...' % PORT
def read_file(file_name, file_type):
print "---------------------------",file_name
f = open(file_name, 'rb')
pic_content = '''\nHTTP/1.x 200 OK\nContent-Type: %s\n\n''' % (file_type)
pic_content = pic_content + f.read()
f.close()
return pic_content
if __name__=='__main__':
init_web()
fun()
upload2.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="form1" method="post" action="/api/upload" enctype="multipart/form-data">
<div>
<input id="File1" type="file" name="file"/> <!--后台代码中获取文件是通过form的name来标识的-->
<input type="submit">提交</input>
</div>
<p>
<a href="download/3.txt" download="33.txt">Download file</a>
</p>
</form>
</body>
</html>