使用Ajax完成图片上传和预览功能
目的
- 将图片预览展示在前端页面
- 将图片上传到后台,数据库中保存图片路径
主要的使用手法
- 前端的form 和 ajax
前端代码:
<form id="form1" enctype="multipart/form-data" style="display: inline-block;padding-left: 40px">
<div class="input-group" style="padding: 20px 40px;margin-top: 40px">
<span class="input-group-addon" id="sizing-addon2">标题</span>
<input style="width: 200px;" type="text" id="articleTitle" class="form-control" placeholder="Username"
aria-describedby="sizing-addon2">
<select id="articleCategory" >
<option value="python">python</option>
<option value="django">django</option>
<option value="basic">basic</option>
</select>
<label for="id_avatar"><img id="avader" src="/static/images/blog/blog-post-thumb-1.jpg" style="width: 30px;height: 30px;"> </label>
<input style="display: inline-block;display: none" type="file" id="id_avatar">
<span id="btnList" style="padding-left: 20px">
<button type="button" id="publishArticle" class="btn btn-info">
发布文章
</button>
</span>
</div>
</form>
在pycharm中的代码格式化功能不太ok,主要看他的包含 enctype="multipart/form-data"
这个就行了
实现预览的功能就要要求我们找到 label
的标签进行操作
预览功能代码:主要是通过修改src来实现
$('#id_avatar').change(function(){
//创建一个读取文件的对象
var fileReader = new FileReader();
//读取文件需要时间
fileReader.readAsDataURL((this.files[0]));
//等待上一步读完文件之后,把图片进行上传
fileReader.onload = function(){
$("#avader").attr("src",fileReader.result);
}
});
通过Ajax进行上传
上传文件的时候必须要使用formdata进行传递
FormData类型其实是在XMLHttpRequest 2级定义的,它是为序列化表以及创建与表单格式相同的数据,为了就是为传递数据提供便利。
$("#publishArticle").click(function(){
var formdata = new FormData();
formdata.append("title",$("#articleTitle").val());
formdata.append("content",$("#articleContent").val());
formdata.append("typeId",$("#articleCategory option:selected").val());
formdata.append("img",$('#id_avatar')[0].files[0]);
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/home/v1/md/',
data: formdata,
dataType: 'json',
cache: false,
//使用ajax传文件必须要使用下面两个
processData:false,
contentType:false,
success: function (arg) {
//debugger;
alert('成功发布')
}
})
})
后台接收
class Md(View):
def get(self,request,*agrs,**kwargs):
return render(request,"Md.html")
def post(self,request,*agrs,**kwargs):
title = request.POST.get('title')
content = request.POST.get('content')
img = request.FILES.get('img')
models.MyContent.objects.create(title=title,content=content,icon=img)
ret = {
'status':1,
'msg':'ok'
}
return JsonResponse(ret,safe=False)
整体效果
希望对你有点帮助,see you !