1 普通上传

1.1 html

<form action="/index/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<p><input type="text" name="user" id="user"></p>
<p><input type="file" name="myFile" id="file"></p>
<input type="submit">
</form>

1.2 views

def index(request):
if request.method == "POST":
print(request.POST)
print(request.FILES)
file_obj = request.FILES.get("myFile")
print(file_obj.name) with open(file_obj.name,"wb") as f:
for line in file_obj:
f.write(line) return HttpResponse("上传成功。")
return render(request, "index.html")

2 基于ajax实现

2.1 Html

<p><input type="file" name="myFile" id="file"></p>
{% csrf_token %}
<button>ajaxSend</button>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script>
$("button").click(function () {
var formdata = new FormData();
formdata.append("imgFile", $("#file")[0].files[0]);
formdata.append("csrfmiddlewaretoken", $("[name='csrfmiddlewaretoken']").val());
$.ajax({
url: "/upload_img/",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (msg) {
console.log(msg)
}
})
})
</script>

2.2 views

import os,json
def upload_img(request):
if request.is_ajax():
obj = request.FILES.get("imgFile")
img_path = os.path.join("static","img",obj.name)
with open(img_path,mode="wb") as f:
for chunk in obj.chunks():
f.write(chunk)
data = {
"status" : True,
"path" : img_path
}
return HttpResponse(json.dumps(data))

3 伪ajax上传

  基于FormData
  缺点:兼容性不好
  优点:Ajax直接发送
  伪Ajax,兼容性更好
    iframe,天生局部刷新
    form,天生整个页面刷新

3.1 html

<input type="text" placeholder="默认值看看刷新之后在不在" />
<form method="POST" target="uploadIframe" action="/upload_img2/" enctype="multipart/form-data">
{% csrf_token %}
<input type="text" name="user" />
<a class="add-pub-btn pub-icons">
上传
<input type="file" name="avatar" id="imgUrl" />
</a>
<input type="submit" value="提交" />
</form>
<iframe id="ifm" name="uploadIframe" onload="successCallback(this);" style="display: none;" ></iframe>
<div id="imgList"></div>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script>
function successCallback(ths){
var response = ths.contentWindow.document.body.innerHTML;
response = JSON.parse(response);
console.log(response);
var img = document.createElement('img');
img.src = "/" + response.data; $('#imgList').append(img);
}
</script>

3.2 views

def upload2(request):
return render(request,"iframe_upload.html") def upload_img2(request):
response = BaseResponse()
try:
obj = request.FILES.get("avatar")
img_path = os.path.join("static","img",obj.name)
with open(img_path,mode="wb") as f:
for chunk in obj.chunks():
for chunk in obj.chunks():
f.write(chunk)
except Exception as e:
response.msg = str(e)
else:
request.status = True
response.data = img_path
return HttpResponse(json.dumps(response.get_dict()))

4 上传按钮美化

4.1 css

<style>
.add-pub-btn {
width: 62px;
height: 31px;
line-height: 31px;
display: block;
text-align: center;
color: #fff;
font-size: 14px;
font-weight: 700;
margin-top: 5px;
cursor: pointer;
}
.pub-icons {
background: url(/static/img/bottom.png?v=2.8) no-repeat 0 0;
}
#imgUrl {
border: 0;
filter: alpha(opacity=0);
background: 0 0;
opacity: 0;
-moz-opacity: 0;
width: 62px;
height: 31px;
left: 5px;
top: 5px\9;
position: absolute;
cursor: pointer;
}
</style>

4.2 按钮设置

<a class="add-pub-btn pub-icons">
上传
<input type="file" name="avatar" id="imgUrl" />
</a>

5 图片预览

本图片的预览功能,主要利用html.js的FileReader进行实现的

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注册</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<style>
#avatar {
margin-top: 5px;
margin-bottom: 5px;
position: relative;
width: 100px;
height: 100px;
} #avatar_img, #file {
width: 100px;
height: 100px;
position: absolute;
left: 15px;
top: 0;
} #file {
opacity: 0;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8" id="avatar">
<img src="default.png" class="img-thumbnail" id="avatar_img">
<input type="file" id="file">
</div>
</div>
</div> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js "></script>
<script type="text/javascript">
// 预览功能
$("#file").change(function () {
var choose_file = $("#file")[0].files[0];
var reader = new FileReader();
reader.readAsDataURL(choose_file);
reader.onload = function () {
$("#avatar_img").attr("src", this.result)
}
});
</script> </body>
</html>

6 文件上传路径

6.1 配置
在settings中配置

MEDIA_ROOT=os.path.join(BASE_DIR,"blog","media")
MEDIA_URL="/media/"

在urls.py中配置

from django.views.static import serve

url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),

6.2 使用

<img src='/media/avatarDir/a.png'>

7 extra

  有些情况下,Django的查询语法难以简单的表达复杂的 WHERE 子句,对于这种情况, Django 提供了 extra() QuerySet修改机制 — 它能在 QuerySet生成的SQL从句中注入新子句
extra可以指定一个或多个 参数,例如 select, where or tables. 这些参数都不是必须的,但是你至少要使用一个!要注意这些额外的方式对不同的数据库引擎可能存在移植性问题.(因为你在显式的书写SQL语句),除非万不得已,尽量避免这样做

# in sqlite:
article_obj=models.Article.objects
              .filter(nid=1)
              .extra(select={"standard_time":"strftime('%%Y-%%m-%%d',create_time)"})
              .values("standard_time","nid","title")
print(article_obj)
# <QuerySet [{'title': 'MongoDb 入门教程', 'standard_time': '2017-09-03', 'nid': 1}]>
current_user = models.UserInfo.objects.filter(username=username).first() #当前用户
【每一步的分析过程】
1、models.Article.objects.all() #查出每一篇文章
2、models.Article.objects.all().filter(user=current_user) #查出当前用户的所有文章
3、models.Article.objects.all().filter(user=current_user).extra(select={"filter_create_date":"strftime('%%Y/%%m',create_time)"}).values_list("filter_create_date")
#查出当前用户的所有文章的create_time,并且只取出年份和月份
解决方案:使用extra方法
extra使用来进行过滤的,参数select必须等于一个字典(转成sql的where语句去执行,查出create_time,然后转换成自己格式化的时间)
4、models.Article.objects.all().filter(user=current_user).extra(select={"filter_create_date":"strftime('%%Y/%%m',create_time)"}).values_list("filter_create_date").annotate(Count("title"))
#按照查询出来的年份和月份进行分组,并且显示文章个数

8 事务使用

from django.contrib.auth import authenticate
with transaction.atomic():
models.ArticleUpDown.objects.create(user_id=user_id, article_id=article_id)
models.Article.objects.filter(nid=article_id).update(up_count=F("up_count") + 1)

django-附件上传、media、extra、事务的更多相关文章

  1. Django文件上传下载与富文本编辑框

    django文件上传下载 上传 配置settings.py # 设定文件的访问路径,如:访问http://127.0.0.1:8000/media/就可以获取文件 MEDIA_URL = '/medi ...

  2. asp.net结合uploadify实现多附件上传

    1.说明 uploadify是一款优秀jQuery插件,主要功能是批量上传文件.大多数同学对多附件上传感到棘手,现将asp.net结合uploadfiy如何实现批量上传附件给大家讲解一下,有什么不对的 ...

  3. ueditor调用其中的附件上传功能

    ueditor实际上是集成了webuploader, 在做内容发布的时候想既有ueditor又有单独的附件上传按钮,这时再加载一个webuploader就显得过于臃肿了,单独利用ueditor的上传功 ...

  4. 基于MVC4+EasyUI的Web开发框架形成之旅--附件上传组件uploadify的使用

    大概一年前,我还在用Asp.NET开发一些行业管理系统的时候,就曾经使用这个组件作为文件的上传操作,在随笔<Web开发中的文件上传组件uploadify的使用>中可以看到,Asp.NET中 ...

  5. 百度在线编辑器UEditor(v1.3.6) .net环境下详细配置教程之更改图片和附件上传路径

    本文是接上一篇博客,如果有疑问请先阅读上一篇:百度在线编辑器UEditor(v1.3.6) .net环境下详细配置教程 默认UEditor上传图片的路径是,编辑器包目录里面的net目录下 下面就演示如 ...

  6. tp中附件上传文件,表单提交

    public function tianjia(){ $goods=D('Goods'); if(!empty($_POST)){ if($_FILES['f_goods_image']['error ...

  7. 使用plupload做一个类似qq邮箱附件上传的效果

    公司项目中使用的框架是springmvc+hibernate+spring,目前需要做一个类似qq邮箱附件上传的功能,暂时只是上传小类型的附件 处理过程和解决方案都需要添加附件,处理过程和解决方案都可 ...

  8. Dynamic CRM 2013学习笔记(十三)附件上传 / 上传附件

    上传附件可能是CRM里比较常用的一个需求了,本文将介绍如何在CRM里实现附件的上传.显示及下载.包括以下几个步骤: 附件上传的web页面 附件显示及下载的附件实体 调用上传web页面的JS文件 实体上 ...

  9. playframework中多附件上传注意事项

    playframework中多附件上传注意事项 2013年09月24日 play 暂无评论 //play版本问题 经确认,1.0.3.2版本下控制器中方法参数  List<File> fi ...

  10. JS实现多附件上传(asp.net)

    前几天,用户提出一个需求-多附件上传,另外,每个上传文件要加一个别名,本人创新少,从网上收集了资料,稍微改写,满足了 客户的需求.在应用到程序之前,先做了个小测试,测试通过,小高兴,就记录下了这个小测 ...

随机推荐

  1. python初步学习-异常

    异常 异常即是一个事件,该事件会在程序执行过程中发生,影响了程序的正常执行. 一般情况下,在python无法正常处理程序时就会发生一个异常. 异常是python对象,表示一个错误. 当python脚本 ...

  2. Linux下搜索命令

    linux下用于查找文件的5个命令,有需要的朋友可以参考下.包括find,whereis,locate,which与type. linux下用于查找文件的5个命令,有需要的朋友可以参考下.包括find ...

  3. 74.VS2013和opencv3.1.0安装教程

    一.先下载文件 1.VS2013 VS2013有很多版本,专业版,旗舰版,中文英文之类的,所对应的密钥也不一样.我选择的是简体中文专业版.下载链接如下. http://www.musnow.com/t ...

  4. UOJ#58/BZOJ 3052【WC2013】糖果公园

    好写好调的莫队算法,就算上树了仍然好写好调. 传送门 http://uoj.ac/problem/58 简要做法 将树按照dfs序分块,然后将询问按照(u所在块,v所在块,时间)作为关键字进行排序,依 ...

  5. java版云笔记(六)之AOP

    今天主要是利用aop技术追加service的响应时间的计算和异常的日志记录. AOP AOP(Aspect Oriented Programming),即面向切面编程,可以说是OOP(Object O ...

  6. 洛谷P2692 覆盖 题解

    题目传送门 这道题一开始想使用二维的bool型数组来存,最后统计.但看到数据范围... 所以就改用两个bool型数组(一维),分别储存横.列,最后将横.列面积求出来,再减去重复算的面积(横的个数*列的 ...

  7. normalize.css阅读笔记

    最近在被各种浏览器的CSS兼容折磨,所以看了看normalize的源代码来了解一些常见的浏览器间不一致的CSS渲染问题…… 源代码在这里 text-size-adjust 用法参见Apple的文档和M ...

  8. Hadoop(八)Hadoop数据压缩与企业级优化

    一 Hadoop数据压缩 1.1 概述 压缩技术能够有效减少底层存储系统(HDFS)读写字节数.压缩提高了网络带宽和磁盘空间的效率.在Hadood下,尤其是数据规模很大和工作负载密集的情况下,使用数据 ...

  9. Nuxt 2.0 需要将pug-loader改成pug-plain-loader

    Nuxt 2.0 需要将pug-loader改成pug-plain-loader npm i pug-plain-loader -D 解决问题!! 参考链接 https://my.oschina.ne ...

  10. 二叉排序树实现(C++封装)

    设计思路 设计一个类,根结点只可读取,具备构造二叉树.插入结点.删除结点.查找. 查找最大值.查找最小值.查找指定结点的前驱和后继等功能接口. 二叉排序树概念 它或者是一棵空树:或者是具有下列性质的二 ...