Python:图片上传
1. 修改界面带回代码
<dl class="nowrap">
<dt>顶部图片:</dt>
<dd>
<textarea id="id_content_{{app_section.id}}" class="textInput" name="obj.content" readonly="1" lookupgroup="obj" cols="106" rows="3">{{app_section.top_icons}}</textarea>
<div id="id_image_lookup_{{app_section.id}}">
<a class="btnLook" href="{{wrap_url(\'app/image/prepare?id=%s\'%app_section.id)}}" lookupgroup="obj" lookuppk="orgNum">上传图片带回</a>
<span style="float:left;line-height:20px;">图片上传</span>
</div>
</dd>
</dl>
2. 跳转弹出框准备(包含已有图片数据请求)
def image__prepare(self):
\'\'\'
准备上传图片
\'\'\'
id = int(self.get_argument(\'id\'))
app_section = AppSectionInfo.mgr().one(id)
top_icons_list = []
img_list = []
top_icons = \'\'
if app_section.top_icons:
top_icons = app_section.get(\'top_icons\').lstrip(\'[\').rstrip(\']\')
top_icons_list = json.loads(app_section.top_icons)
for i in top_icons_list:
img_list.append(i.get("imgUrl"))
self.render(\'app/image_upload.html\',
app_section = app_section,
top_icons = top_icons,
img_list = img_list)
3. 弹出框界面代码示例
<style>
.pageFormContent dl.nowrap dd {width:400px;}
</style>
<div class="pageContent">
<form method="post" action="{{wrap_url(\'app/image/upload\')}}" class="required-validate" enctype="multipart/form-data" onsubmit="return iframeCallback(this, imageuploadAjaxDone);">
<div class="pageFormContent" layoutH="56">
<fieldset style=\'border:0px;\'>
<dl class="nowrap">
<dt>上传图片:</dt>
<dd>
<textarea id="id_all_files" class="textInput" name="all_files" readonly="true" cols="80" rows="3">{{top_icons}}</textare
a>
</dd>
</dl>
<dl class="nowrap">
<dt>跳转url:</dt>
<dd>
<input id="id_img_skip" name="img_skip" type="text" size="90">
</dd>
</dl>
<dl class="nowrap">
<dt>图片提示:</dt>
<dd>
<input id="id_img_tip" name="img_tip" type="text" size="43">
</dd>
</dl>
<dl class="nowrap">
<dt>上传图片:</dt>
<dd>
<input type="hidden" name="id" value="{{app_section.id}}"/>
<input id="id_file_name" type="file" name="file" class="required" size="60">
</dd>
</dl>
<dl id="id_image_browse" class="nowrap" {% if not img_list %}style="display:none;"{%end%}>
{% for i in img_list %}
<img src="{{wrap_static_url(\'pics/%s\'%i)}}" width="80" height="80" />
<span >{{extract_ad_image_size(i)}}
<a href="#" onclick="javascript:ajax_delete_image(\'{{i}}\');return false;">删除</a>
</span>
{% end %}
</dl>
</fieldset>
</div>
<div class="formBar">
<ul>
<li><div class="buttonActive"><div class="buttonContent"><button type="submit">上传</button></div></div></li>
<li>
<div class="button">
<div class="buttonContent">
<button type="button" onclick="javascript:bringback();" warn="请上传文件">确认</button>
</div></div>
</li>
<li>
<div class="button"><div class="buttonContent"><button type="button" class="close">取消</button></div></div>
</li>
</ul>
</div>
</form>
</div>
<form name="image_delete_form_{{app_section.id}}" method="post" action="app/image/delete" onsubmit="return validateCallback(this, imageuploadAjaxDone);">
<input type="hidden" name="id" value="{{app_section.id}}"/>
<input type="hidden" name="file_name" />
</form>
<script>
function ajax_delete_image(file_name){
$.ajax({
type: \'GET\',
url:"{{wrap_url(\'/app/image/delete\')}}",
data:"id={{app_section.id}}&file_name="+file_name,
dataType:"json",
cache: false,
success: imageuploadAjaxDone
});
}
4. 图片上传过程
def image__upload(self):
\'\'\'
上传图片
id:应用推荐榜单ID
image_type: 8,专用于应用推荐分类
use_for: 用途,默认为a
路径格式: {image_type}/{use_for}/{suffix}/{adapter}/{filename}
\'\'\'
id = int(self.get_argument(\'id\'))
img_skip = self.get_argument(\'img_skip\',\'\')
img_tip = self.get_argument(\'img_tip\',\'\')
image_type,use_for = \'8\',\'a\'
base_path = os.path.join(self.application.settings[\'static_path\'],\'pics\')
msg = \'\'
file_name_list = []
for f in self.request.files[\'file\']:
suffix = os.path.splitext(f["filename"])[1].lower()
if suffix not in (\'.jpg\',\'.png\'):
msg = \'文件格式有误,只能是jpg或者png\'
break
else:
width,height = Image.open(StringIO.StringIO(f["body"])).size
adapter = \'%s%s\' % (width,height)
prefix_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
name = \'%s%s\' % (prefix_name,suffix)
full_path = os.path.join(base_path,image_type,use_for,suffix[1:],adapter)
full_name = os.path.join(full_path,name)
if not os.path.exists(full_path):
os.makedirs(full_path)
with open(full_name,\'w+b\') as fp:
fp.write(f[\'body\'])
file_name_list.append(full_name.replace(base_path,\'\')[1:])
#将上传参数拼接成json串
result = []
for fname in file_name_list:
record = {"imgSkip":img_skip,"imgTip":img_tip,"imgUrl":fname}
result.append(record)
if msg:
self.json2dwz(\'300\',\'\',msg=msg)
else:
self.json2dwz(\'200\',\'\',content=json.dumps(result))
5. 图片删除
def image__delete(self):
\'\'\'
删除图片
id: 推荐榜单ID
\'\'\'
id = int(self.get_argument(\'id\'))
app_section = AppSectionInfo.mgr(ismaster=1).one(id)
file_name = self.get_argument(\'file_name\')
top_icons_list = json.loads(app_section.top_icons)
file_name_list = []
for top_icon in top_icons_list:
if file_name==top_icon.get("imgUrl"):
top_icons_list.remove(top_icon)
else:
file_name_list.append(top_icon)
app_section.top_icons = str(top_icons_list)
app_section.save()
#AppSectionInfo.mgr(ismaster=1).raw("update app_section_info set top_icons=\'%s\' where id=%s"%(top_icons_str,id),())
base_path = os.path.join(self.application.settings[\'static_path\'],\'pics\')
full_name = os.path.join(base_path,file_name)
# 调用图片系统删除图片的接口
if os.path.exists(full_name):
os.remove(full_name)
result = str(json.dumps(file_name_list)).lstrip(\'[\').rstrip(\']\')
self.json2dwz(\'200\',\'delete\',content=result)