菜鸟学习
在一个table中涉及下载,url传参始终不能下载,经过摸索终于实现,图片如下,点击下载进行下载
js代码:
formatter:function(value,row,index){
var id = value;
var result = "";
if(id!="null" ){
result = "+ id +" \" class='btn btn-xs blue' title='下载' id='DownLoad'>下载"; }
else{
result =""
}
return result
}
在JS内部尝试的必须使用这种方法
<a href=\"/FileDown_Alarm/?filename="+ id +" \">
使用{%url “地址” 变量 %} 标签无法识别,解析不出,不知道为什么
使用ajax方式上传,参数可以传过去,但是不能触发下载,搜了一下,好像ajax不支持流下载
url:
文件上传
url(r'^Save_Alarm_Record/$', Alarm.Save_Alarm_Record,name="Save_Alarm_Record"),
文件下载
url(r'^FileDown_Alarm/$', Alarm.FileDown_Alarm, name="FileDown_Alarm"),
值得注意的是路径问题,网上的很多下载的资料不支持中文字符路径,优化后
文件下载
view.py
def FileDown_Alarm(request):
file_name=request.GET.get('filename')
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # 项目根目录
file_path = os.path.join(base_dir, 'UploadFiles', 'Alarm', file_name) # 下载文件的绝对路径
#if not os.path.isfile(file_path): # 判断下载文件是否存在
# return HttpResponse("Sorry but Not Found the File!")
try:
file = open(file_path, 'rb')
response =FileResponse(file)
response['Content-Type']='application/octet-stream'
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name))
except:
return HttpResponse("Sorry but Download the File Failed!")
return response
需要引入:from django.utils.encoding import escape_uri_path
下载写法:
from django.utils.encoding import escape_uri_path
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file_name))
都是些小知识,请教别人也不给讲,废了好大劲。在此分享一下,也自己做个笔记
补充上传代码
文件上传
def Save_Alarm_Record(request):
post = request.POST
FileR = request.FILES.get('FileR')
try:
filename=""
if FileR :
filename = FileR.name
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
filepath = os.path.join(BASE_DIR, 'UploadFiles', 'Alarm', FileR.name)
f = open(filepath, 'wb')
for chunk in FileR.chunks():
f.write(chunk)
f.close()
else:
filename = "null"
except:
return HttpResponse("Save File Failed!")
return HttpResponse('OK')