上传组件bootstrap-fileinput
接收代码(python版)
以流的方式接收,写入文件
attachment_obj = req.FILES.get("file_data")
file_name = attachment_obj._name
# module_path = os.path.split(os.path.realpath(__file__))[0]
module_path = SQL_ATTACHMENT_DIR
timestamp_dir = time.strftime("%Y%m%d")
# 判断目录是否存在
if not os.path.exists("{0}/sql_tmp/{1}".format(module_path, timestamp_dir)):
os.makedirs("{0}/sql_tmp/{1}".format(module_path, timestamp_dir))
# 判断当前目录下,文件名是否同名
if os.path.exists("{0}/sql_tmp/{1}/{2}".format(module_path, timestamp_dir, file_name)):
return JsonResponse("已存在, 上传失败".format(file_name), safe=False)
with open("{0}/sql_tmp/{1}/{2}".format(module_path, timestamp_dir, file_name), 'wb+') as f:
for chunk in attachment_obj.file:
f.write(chunk)
return JsonResponse("success", safe=False)
存储
文件名与流程数据以外键依赖关系存于db
在一个大目录下,再以日期建小目录存储
下载
下载请求不能用ajax形式,因为ajax不支持流方式数据。
可以用form封装请求:
window.attachmentEvents = {
'click .attachment_down': function (e, value, form_data) {
var filename = form_data.attachment
var timestamp = form_data.create_date
const currentUrl = window.location.href
var url = currentUrl + "sql/attachment/download/"
var form=$("<form>");//定义一个form表单
form.attr("style","display:none");
form.attr("target","");
form.attr("method","get"); //请求类型
form.attr("action",url); //请求地址
var struct_input_filename=$("<input>");
var struct_input_timestamp=$("<input>");
struct_input_filename.attr("type","hidden");
struct_input_filename.attr("name","filename");
struct_input_filename.attr("value",filename);
struct_input_timestamp.attr("type","hidden");
struct_input_timestamp.attr("name","timestamp");
struct_input_timestamp.attr("value",timestamp);
form.append(struct_input_filename);
form.append(struct_input_timestamp);
$(document.body).append(form)
form.submit()
}
后端下载api
file_name = req.GET.get("filename")
timestamp = req.GET.get("timestamp")
date_dir = timestamp[0:8]
# module_path = os.path.split(os.path.realpath(__file__))[0]
module_path = SQL_ATTACHMENT_DIR
def file_iterator(file_name, chunk_size=8192):
with open("{0}/sql_tmp/{1}/{2}".format(module_path, date_dir, file_name), 'rb') as f:
while True:
c = f.read(chunk_size)
if c:
yield c
else:
break
response = StreamingHttpResponse(file_iterator(file_name))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = "attachment;filename='{0}'".format(file_name)
return response